Unnamed: 0
int64
0
6.7k
func
stringlengths
12
89.6k
target
bool
2 classes
project
stringlengths
45
151
2,900
private static class Consumer extends PropertyTypeDispatcher<String, Void> { private final MappingWriter writer; Consumer( MappingWriter serializer ) { this.writer = serializer; } @Override protected Void dispatchBooleanProperty( boolean property, String param ) { writer.writeBoolean( param, property ); return null; } @Override protected Void dispatchByteProperty( byte property, String param ) { writer.writeInteger( RepresentationType.BYTE, param, property ); return null; } @Override protected Void dispatchCharacterProperty( char property, String param ) { writer.writeInteger( RepresentationType.CHAR, param, property ); return null; } @Override protected Void dispatchDoubleProperty( double property, String param ) { writer.writeFloatingPointNumber( RepresentationType.DOUBLE, param, property ); return null; } @Override protected Void dispatchFloatProperty( float property, String param ) { writer.writeFloatingPointNumber( RepresentationType.FLOAT, param, property ); return null; } @Override protected Void dispatchIntegerProperty( int property, String param ) { writer.writeInteger( RepresentationType.INTEGER, param, property ); return null; } @Override protected Void dispatchLongProperty( long property, String param ) { writer.writeInteger( RepresentationType.LONG, param, property ); return null; } @Override protected Void dispatchShortProperty( short property, String param ) { writer.writeInteger( RepresentationType.SHORT, param, property ); return null; } @Override protected Void dispatchStringProperty( String property, String param ) { writer.writeString( param, property ); return null; } @Override protected Void dispatchStringArrayProperty( String[] property, String param ) { ListWriter list = writer.newList( RepresentationType.STRING, param ); for ( String s : property ) { list.writeString( s ); } list.done(); return null; } @Override @SuppressWarnings( "boxing" ) protected Void dispatchByteArrayProperty( PropertyArray<byte[], Byte> array, String param ) { ListWriter list = writer.newList( RepresentationType.BYTE, param ); for ( Byte b : array ) { list.writeInteger( RepresentationType.BYTE, b ); } list.done(); return null; } @Override @SuppressWarnings( "boxing" ) protected Void dispatchShortArrayProperty( PropertyArray<short[], Short> array, String param ) { ListWriter list = writer.newList( RepresentationType.SHORT, param ); for ( Short s : array ) { list.writeInteger( RepresentationType.SHORT, s ); } list.done(); return null; } @Override @SuppressWarnings( "boxing" ) protected Void dispatchCharacterArrayProperty( PropertyArray<char[], Character> array, String param ) { ListWriter list = writer.newList( RepresentationType.CHAR, param ); for ( Character c : array ) { list.writeInteger( RepresentationType.CHAR, c ); } list.done(); return null; } @Override @SuppressWarnings( "boxing" ) protected Void dispatchIntegerArrayProperty( PropertyArray<int[], Integer> array, String param ) { ListWriter list = writer.newList( RepresentationType.INTEGER, param ); for ( Integer i : array ) { list.writeInteger( RepresentationType.INTEGER, i ); } list.done(); return null; } @Override @SuppressWarnings( "boxing" ) protected Void dispatchLongArrayProperty( PropertyArray<long[], Long> array, String param ) { ListWriter list = writer.newList( RepresentationType.LONG, param ); for ( Long j : array ) { list.writeInteger( RepresentationType.LONG, j ); } list.done(); return null; } @Override @SuppressWarnings( "boxing" ) protected Void dispatchFloatArrayProperty( PropertyArray<float[], Float> array, String param ) { ListWriter list = writer.newList( RepresentationType.FLOAT, param ); for ( Float f : array ) { list.writeFloatingPointNumber( RepresentationType.FLOAT, f ); } list.done(); return null; } @Override @SuppressWarnings( "boxing" ) protected Void dispatchDoubleArrayProperty( PropertyArray<double[], Double> array, String param ) { ListWriter list = writer.newList( RepresentationType.DOUBLE, param ); for ( Double d : array ) { list.writeFloatingPointNumber( RepresentationType.DOUBLE, d ); } list.done(); return null; } @Override @SuppressWarnings( "boxing" ) protected Void dispatchBooleanArrayProperty( PropertyArray<boolean[], Boolean> array, String param ) { ListWriter list = writer.newList( RepresentationType.BOOLEAN, param ); for ( Boolean z : array ) { list.writeBoolean( z ); } list.done(); return null; } }
false
community_server_src_main_java_org_neo4j_server_rest_repr_PropertiesRepresentation.java
2,901
class RepresentationTestBase { static final URI BASE_URI = URI.create( "http://neo4j.org/" ); static final String NODE_URI_PATTERN = "http://.*/node/[0-9]+"; static final String RELATIONSHIP_URI_PATTERN = "http://.*/relationship/[0-9]+"; static void assertUriMatches( String expectedRegex, ValueRepresentation uriRepr ) { assertUriMatches( expectedRegex, RepresentationTestAccess.serialize( uriRepr ) ); } static void assertUriMatches( String expectedRegex, URI actualUri ) { assertUriMatches( expectedRegex, actualUri.toString() ); } static void assertUriMatches( String expectedRegex, String actualUri ) { assertTrue( "expected <" + expectedRegex + "> got <" + actualUri + ">", actualUri.matches( expectedRegex ) ); } static String uriPattern( String subPath ) { return "http://.*/[0-9]+" + subPath; } private RepresentationTestBase() { // only static resource } }
false
community_server_src_test_java_org_neo4j_server_rest_repr_RepresentationTestBase.java
2,902
{ @Override public void onRepresentationStartWriting() { // do nothing } @Override public void onRepresentationWritten() { // do nothing } @Override public void onRepresentationFinal() { // do nothing } };
false
community_server_src_main_java_org_neo4j_server_rest_repr_RepresentationWriteHandler.java
2,903
private static class ParameterRepresentation extends MappingRepresentation { private final String name; private final RepresentationType paramType; private final String description; private final boolean optional; private final boolean list; ParameterRepresentation( String name, Class<?> type, boolean optional, String description, boolean list ) { super( RepresentationType.PLUGIN_PARAMETER ); this.name = name; this.optional = optional; this.list = list; this.paramType = RepresentationType.extended( type ); this.description = description; } @Override protected void serialize( MappingSerializer serializer ) { serializer.putString( "name", name ); serializer.putString( "type", list ? paramType.listName : paramType.valueName ); serializer.putBoolean( "optional", optional ); serializer.putString( "description", description ); } }
false
community_server_src_main_java_org_neo4j_server_rest_repr_ExtensionPointRepresentation.java
2,904
public class SchemaIndexRepresentationTest { @Test public void shouldIncludeLabel() throws Exception { // GIVEN String labelName = "person", propertyKey = "name"; IndexDefinition definition = mock( IndexDefinition.class ); when( definition.getLabel() ).thenReturn( label( labelName ) ); when( definition.getPropertyKeys() ).thenReturn( asList( propertyKey ) ); IndexDefinitionRepresentation representation = new IndexDefinitionRepresentation( definition ); Map<String, Object> serialized = RepresentationTestAccess.serialize( representation ); // THEN assertEquals( asList( propertyKey ), serialized.get( "property_keys" ) ); assertEquals( labelName, serialized.get( "label" ) ); } }
false
community_server_src_test_java_org_neo4j_server_rest_repr_SchemaIndexRepresentationTest.java
2,905
NODE( Representation.NODE ) { @Override String render( Map<String, Object> serialized ) { return JsonHelper.createJsonFrom( MapUtil.map( "self", serialized.get( "self" ), "data", serialized.get( "data" ) ) ); } },
false
community_server_src_main_java_org_neo4j_server_rest_repr_formats_CompactJsonFormat.java
2,906
private static class CompactJsonWriter extends MapWrappingWriter { private final MappingTemplate template; public CompactJsonWriter( MappingTemplate template ) { super( new HashMap<String, Object>(), true ); this.template = template; } @Override protected MappingWriter newMapping( String type, String key ) { Map<String, Object> map = new HashMap<String, Object>(); data.put( key, map ); return new MapWrappingWriter( map, interactive ); } @Override protected void writeValue( String type, String key, Object value ) { data.put( key, value ); } @Override protected ListWriter newList( String type, String key ) { List<Object> list = new ArrayList<Object>(); data.put( key, list ); return new ListWrappingWriter( list, interactive ); } String complete() { return template.render( this.data ); } }
false
community_server_src_main_java_org_neo4j_server_rest_repr_formats_CompactJsonFormat.java
2,907
@Service.Implementation( RepresentationFormat.class ) public class CompactJsonFormat extends RepresentationFormat { public static final MediaType MEDIA_TYPE = new MediaType( MediaType.APPLICATION_JSON_TYPE.getType(), MediaType.APPLICATION_JSON_TYPE.getSubtype(), MapUtil.stringMap( "compact", "true" ) ); public CompactJsonFormat() { super( MEDIA_TYPE ); } private enum MappingTemplate { NODE( Representation.NODE ) { @Override String render( Map<String, Object> serialized ) { return JsonHelper.createJsonFrom( MapUtil.map( "self", serialized.get( "self" ), "data", serialized.get( "data" ) ) ); } }, RELATIONSHIP( Representation.RELATIONSHIP ) { @Override String render( Map<String, Object> serialized ) { return JsonHelper.createJsonFrom( MapUtil.map( "self", serialized.get( "self" ), "data", serialized.get( "data" ) ) ); } }, STRING( Representation.STRING ) { @Override String render( Map<String, Object> serialized ) { return JsonHelper.createJsonFrom( serialized ); } }, EXCEPTION( Representation.EXCEPTION ) { @Override String render( Map<String, Object> data ) { return JsonHelper.createJsonFrom( data ); } }; private final String key; private MappingTemplate( String key ) { this.key = key; } static final Map<String, MappingTemplate> TEMPLATES = new HashMap<String, MappingTemplate>(); static { for ( MappingTemplate template : values() ) TEMPLATES.put( template.key, template ); } abstract String render( Map<String, Object> data ); } private static class CompactJsonWriter extends MapWrappingWriter { private final MappingTemplate template; public CompactJsonWriter( MappingTemplate template ) { super( new HashMap<String, Object>(), true ); this.template = template; } @Override protected MappingWriter newMapping( String type, String key ) { Map<String, Object> map = new HashMap<String, Object>(); data.put( key, map ); return new MapWrappingWriter( map, interactive ); } @Override protected void writeValue( String type, String key, Object value ) { data.put( key, value ); } @Override protected ListWriter newList( String type, String key ) { List<Object> list = new ArrayList<Object>(); data.put( key, list ); return new ListWrappingWriter( list, interactive ); } String complete() { return template.render( this.data ); } } @Override protected ListWriter serializeList( String type ) { return new ListWrappingWriter( new ArrayList<Object>() ); } @Override protected String complete( ListWriter serializer ) { return JsonHelper.createJsonFrom( ( (ListWrappingWriter) serializer ).data ); } @Override protected MappingWriter serializeMapping( String type ) { MappingTemplate template = MappingTemplate.TEMPLATES.get( type ); if ( template == null ) { throw new WebApplicationException( Response.status( Response.Status.NOT_ACCEPTABLE ) .entity( "Cannot represent \"" + type + "\" as compactJson" ) .build() ); } return new CompactJsonWriter( template ); } @Override protected String complete( MappingWriter serializer ) { return ( (CompactJsonWriter) serializer ).complete(); } @Override protected String serializeValue( String type, Object value ) { return JsonHelper.createJsonFrom( value ); } private boolean empty( String input ) { return input == null || "".equals( input.trim() ); } @Override public Map<String, Object> readMap( String input, String... requiredKeys ) throws BadInputException { if ( empty( input ) ) return DefaultFormat.validateKeys( Collections.<String,Object>emptyMap(), requiredKeys ); try { return DefaultFormat.validateKeys( JsonHelper.jsonToMap( stripByteOrderMark( input ) ), requiredKeys ); } catch ( JsonParseException ex ) { throw new BadInputException( ex ); } } @Override public List<Object> readList( String input ) { // TODO tobias: Implement readList() [Dec 10, 2010] throw new UnsupportedOperationException( "Not implemented: JsonInput.readList()" ); } @Override public Object readValue( String input ) throws BadInputException { if ( empty( input ) ) return Collections.emptyMap(); try { return JsonHelper.jsonToSingleValue( stripByteOrderMark( input ) ); } catch ( JsonParseException ex ) { throw new BadInputException( ex ); } } @Override public URI readUri( String input ) throws BadInputException { try { return new URI( readValue( input ).toString() ); } catch ( URISyntaxException e ) { throw new BadInputException( e ); } } private String stripByteOrderMark( String string ) { if ( string != null && string.length() > 0 && string.charAt( 0 ) == 0xfeff ) { return string.substring( 1 ); } return string; } }
false
community_server_src_main_java_org_neo4j_server_rest_repr_formats_CompactJsonFormat.java
2,908
public class WeightedPathRepresentation extends PathRepresentation<WeightedPath> { public WeightedPathRepresentation( WeightedPath path ) { super( path ); } @Mapping( "weight" ) public ValueRepresentation weight() { return ValueRepresentation.number( getPath().weight() ); } }
false
community_server_src_main_java_org_neo4j_server_rest_repr_WeightedPathRepresentation.java
2,909
{ @Override protected Representation underlyingObjectToObject( Object object ) { return property( object ); } };
false
community_server-api_src_main_java_org_neo4j_server_rest_repr_ValueRepresentation.java
2,910
{ @Override protected Representation dispatchBooleanProperty( boolean property, Void param ) { return bool( property ); } @Override protected Representation dispatchByteProperty( byte property, Void param ) { return new ValueRepresentation( RepresentationType.BYTE, property ); } @Override protected Representation dispatchCharacterProperty( char property, Void param ) { return new ValueRepresentation( RepresentationType.CHAR, property ); } @Override protected Representation dispatchDoubleProperty( double property, Void param ) { return new ValueRepresentation( RepresentationType.DOUBLE, property ); } @Override protected Representation dispatchFloatProperty( float property, Void param ) { return new ValueRepresentation( RepresentationType.FLOAT, property ); } @Override protected Representation dispatchIntegerProperty( int property, Void param ) { return new ValueRepresentation( RepresentationType.INTEGER, property ); } @Override protected Representation dispatchLongProperty( long property, Void param ) { return new ValueRepresentation( RepresentationType.LONG, property ); } @Override protected Representation dispatchShortProperty( short property, Void param ) { return new ValueRepresentation( RepresentationType.SHORT, property ); } @Override protected Representation dispatchStringProperty( String property, Void param ) { return string( property ); } @Override protected Representation dispatchStringArrayProperty( String[] property, Void param ) { return ListRepresentation.strings( property ); } @SuppressWarnings( "unchecked" ) private Iterable<Representation> dispatch( PropertyArray<?, ?> array ) { return new IterableWrapper<Representation, Object>( (Iterable<Object>) array ) { @Override protected Representation underlyingObjectToObject( Object object ) { return property( object ); } }; } @Override @SuppressWarnings( "boxing" ) protected Representation dispatchByteArrayProperty( PropertyArray<byte[], Byte> array, Void param ) { return toListRepresentation(RepresentationType.BYTE, array); } @Override @SuppressWarnings( "boxing" ) protected Representation dispatchShortArrayProperty( PropertyArray<short[], Short> array, Void param ) { return toListRepresentation(RepresentationType.SHORT, array); } private ListRepresentation toListRepresentation(RepresentationType type, PropertyArray<?, ?> array) { return new ListRepresentation(type, dispatch(array) ); } @Override @SuppressWarnings( "boxing" ) protected Representation dispatchCharacterArrayProperty( PropertyArray<char[], Character> array, Void param ) { return toListRepresentation(RepresentationType.CHAR, array); } @Override @SuppressWarnings( "boxing" ) protected Representation dispatchIntegerArrayProperty( PropertyArray<int[], Integer> array, Void param ) { return toListRepresentation(RepresentationType.INTEGER, array); } @Override @SuppressWarnings( "boxing" ) protected Representation dispatchLongArrayProperty( PropertyArray<long[], Long> array, Void param ) { return toListRepresentation(RepresentationType.LONG, array); } @Override @SuppressWarnings( "boxing" ) protected Representation dispatchFloatArrayProperty( PropertyArray<float[], Float> array, Void param ) { return toListRepresentation(RepresentationType.FLOAT, array); } @Override @SuppressWarnings( "boxing" ) protected Representation dispatchDoubleArrayProperty( PropertyArray<double[], Double> array, Void param ) { return toListRepresentation(RepresentationType.DOUBLE, array); } @Override @SuppressWarnings( "boxing" ) protected Representation dispatchBooleanArrayProperty( PropertyArray<boolean[], Boolean> array, Void param ) { return toListRepresentation(RepresentationType.BOOLEAN, array); } };
false
community_server-api_src_main_java_org_neo4j_server_rest_repr_ValueRepresentation.java
2,911
{ @Override String serialize( RepresentationFormat format, URI baseUri, ExtensionInjector extensions ) { return Serializer.joinBaseWithRelativePath( baseUri, path ); } @Override void addTo( ListSerializer serializer ) { serializer.addUriTemplate( path ); } @Override void putTo( MappingSerializer serializer, String key ) { serializer.putUriTemplate( key, path ); } };
false
community_server-api_src_main_java_org_neo4j_server_rest_repr_ValueRepresentation.java
2,912
{ @Override String serialize( RepresentationFormat format, URI baseUri, ExtensionInjector extensions ) { return Serializer.joinBaseWithRelativePath( baseUri, path ); } @Override void addTo( ListSerializer serializer ) { serializer.addUri( path ); } @Override void putTo( MappingSerializer serializer, String key ) { serializer.putUri( key, path ); } };
false
community_server-api_src_main_java_org_neo4j_server_rest_repr_ValueRepresentation.java
2,913
public class ValueRepresentation extends Representation { private final Object value; private ValueRepresentation( RepresentationType type, Object value ) { super( type ); this.value = value; } @Override String serialize( RepresentationFormat format, URI baseUri, ExtensionInjector extensions ) { final String result = format.serializeValue(type, value); format.complete(); return result; } @Override void addTo( ListSerializer serializer ) { serializer.writer.writeValue( type, value ); } @Override void putTo( MappingSerializer serializer, String key ) { serializer.writer.writeValue( type, key, value ); } public static ValueRepresentation ofNull() { return new ValueRepresentation( RepresentationType.NULL, null ); } public static ValueRepresentation string( String value ) { return new ValueRepresentation( RepresentationType.STRING, value ); } @SuppressWarnings( "boxing" ) public static ValueRepresentation number( int value ) { return new ValueRepresentation( RepresentationType.INTEGER, value ); } @SuppressWarnings( "boxing" ) public static ValueRepresentation number( long value ) { return new ValueRepresentation( RepresentationType.LONG, value ); } @SuppressWarnings( "boxing" ) public static ValueRepresentation number( double value ) { return new ValueRepresentation( RepresentationType.DOUBLE, value ); } public static ValueRepresentation bool( boolean value ) { return new ValueRepresentation( RepresentationType.BOOLEAN, value ); } public static ValueRepresentation relationshipType( RelationshipType type ) { return new ValueRepresentation( RepresentationType.RELATIONSHIP_TYPE, type.name() ); } public static ValueRepresentation uri( final String path ) { return new ValueRepresentation( RepresentationType.URI, null ) { @Override String serialize( RepresentationFormat format, URI baseUri, ExtensionInjector extensions ) { return Serializer.joinBaseWithRelativePath( baseUri, path ); } @Override void addTo( ListSerializer serializer ) { serializer.addUri( path ); } @Override void putTo( MappingSerializer serializer, String key ) { serializer.putUri( key, path ); } }; } public static ValueRepresentation template( final String path ) { return new ValueRepresentation( RepresentationType.TEMPLATE, null ) { @Override String serialize( RepresentationFormat format, URI baseUri, ExtensionInjector extensions ) { return Serializer.joinBaseWithRelativePath( baseUri, path ); } @Override void addTo( ListSerializer serializer ) { serializer.addUriTemplate( path ); } @Override void putTo( MappingSerializer serializer, String key ) { serializer.putUriTemplate( key, path ); } }; } static Representation property( Object property ) { return PROPERTY_REPRESENTATION.dispatch( property, null ); } private static final PropertyTypeDispatcher<Void, Representation> PROPERTY_REPRESENTATION = new PropertyTypeDispatcher<Void, Representation>() { @Override protected Representation dispatchBooleanProperty( boolean property, Void param ) { return bool( property ); } @Override protected Representation dispatchByteProperty( byte property, Void param ) { return new ValueRepresentation( RepresentationType.BYTE, property ); } @Override protected Representation dispatchCharacterProperty( char property, Void param ) { return new ValueRepresentation( RepresentationType.CHAR, property ); } @Override protected Representation dispatchDoubleProperty( double property, Void param ) { return new ValueRepresentation( RepresentationType.DOUBLE, property ); } @Override protected Representation dispatchFloatProperty( float property, Void param ) { return new ValueRepresentation( RepresentationType.FLOAT, property ); } @Override protected Representation dispatchIntegerProperty( int property, Void param ) { return new ValueRepresentation( RepresentationType.INTEGER, property ); } @Override protected Representation dispatchLongProperty( long property, Void param ) { return new ValueRepresentation( RepresentationType.LONG, property ); } @Override protected Representation dispatchShortProperty( short property, Void param ) { return new ValueRepresentation( RepresentationType.SHORT, property ); } @Override protected Representation dispatchStringProperty( String property, Void param ) { return string( property ); } @Override protected Representation dispatchStringArrayProperty( String[] property, Void param ) { return ListRepresentation.strings( property ); } @SuppressWarnings( "unchecked" ) private Iterable<Representation> dispatch( PropertyArray<?, ?> array ) { return new IterableWrapper<Representation, Object>( (Iterable<Object>) array ) { @Override protected Representation underlyingObjectToObject( Object object ) { return property( object ); } }; } @Override @SuppressWarnings( "boxing" ) protected Representation dispatchByteArrayProperty( PropertyArray<byte[], Byte> array, Void param ) { return toListRepresentation(RepresentationType.BYTE, array); } @Override @SuppressWarnings( "boxing" ) protected Representation dispatchShortArrayProperty( PropertyArray<short[], Short> array, Void param ) { return toListRepresentation(RepresentationType.SHORT, array); } private ListRepresentation toListRepresentation(RepresentationType type, PropertyArray<?, ?> array) { return new ListRepresentation(type, dispatch(array) ); } @Override @SuppressWarnings( "boxing" ) protected Representation dispatchCharacterArrayProperty( PropertyArray<char[], Character> array, Void param ) { return toListRepresentation(RepresentationType.CHAR, array); } @Override @SuppressWarnings( "boxing" ) protected Representation dispatchIntegerArrayProperty( PropertyArray<int[], Integer> array, Void param ) { return toListRepresentation(RepresentationType.INTEGER, array); } @Override @SuppressWarnings( "boxing" ) protected Representation dispatchLongArrayProperty( PropertyArray<long[], Long> array, Void param ) { return toListRepresentation(RepresentationType.LONG, array); } @Override @SuppressWarnings( "boxing" ) protected Representation dispatchFloatArrayProperty( PropertyArray<float[], Float> array, Void param ) { return toListRepresentation(RepresentationType.FLOAT, array); } @Override @SuppressWarnings( "boxing" ) protected Representation dispatchDoubleArrayProperty( PropertyArray<double[], Double> array, Void param ) { return toListRepresentation(RepresentationType.DOUBLE, array); } @Override @SuppressWarnings( "boxing" ) protected Representation dispatchBooleanArrayProperty( PropertyArray<boolean[], Boolean> array, Void param ) { return toListRepresentation(RepresentationType.BOOLEAN, array); } }; }
false
community_server-api_src_main_java_org_neo4j_server_rest_repr_ValueRepresentation.java
2,914
public class TestExceptionRepresentation { @Test public void shouldIncludeCause() throws Exception { // Given ExceptionRepresentation rep = new ExceptionRepresentation( new RuntimeException("Hoho", new RuntimeException("Haha", new RuntimeException( "HAHA!" )) )); Map<String, Object> output = new HashMap<String, Object>(); MappingSerializer serializer = new MappingSerializer( new MapWrappingWriter(output), URI.create( "" ), mock(ExtensionInjector.class ) ); // When rep.serialize( serializer ); // Then assertThat(output.containsKey( "cause" ), is( true )); assertThat( output.get( "cause" ), is( instanceOf( Map.class ) ) ); assertThat( (String) ((Map<String,Object>)output.get( "cause" )).get("message"), is( "Haha" ) ); assertThat( ( (Map<String, Object>) output.get( "cause" ) ).get( "cause" ), is( instanceOf( Map.class ) ) ); assertThat( (String) ((Map<String,Object>)((Map<String,Object>)output.get( "cause" )).get("cause")).get( "message" ), is( "HAHA!") ); } }
false
community_server_src_test_java_org_neo4j_server_rest_repr_TestExceptionRepresentation.java
2,915
public class ServerListRepresentation extends ListRepresentation { public ServerListRepresentation( RepresentationType type, Iterable<? extends Representation> content ) { super( type, content ); } protected void serialize( ListSerializer serializer ) { for ( Object val : content ) { if (val instanceof Number) serializer.addNumber( (Number) val ); else if (val instanceof String) serializer.addString( (String) val ); else if (val instanceof Iterable) serializer.addList( ObjectToRepresentationConverter.getListRepresentation( (Iterable) val ) ); else if (val instanceof Map) serializer.addMapping( ObjectToRepresentationConverter.getMapRepresentation( (Map) val ) ); else if (val instanceof MappingRepresentation) serializer.addMapping( (MappingRepresentation) val ); else if (val instanceof Representation) ((Representation)val).addTo( serializer ); //default else serializer.addString( val.toString() ); } } }
false
community_server_src_main_java_org_neo4j_server_rest_repr_ServerListRepresentation.java
2,916
private static class EntityExtensionRepresentation extends MappingRepresentation { private final List<ExtensionPointRepresentation> extensions; EntityExtensionRepresentation() { super( "entity-extensions" ); this.extensions = new ArrayList<ExtensionPointRepresentation>(); } void add( ExtensionPointRepresentation extension ) { extensions.add( extension ); } @Override protected void serialize( MappingSerializer serializer ) { for ( ExtensionPointRepresentation extension : extensions ) { serializer.putMapping( extension.getName(), extension ); } } }
false
community_server_src_main_java_org_neo4j_server_rest_repr_ServerExtensionRepresentation.java
2,917
public final class ServerExtensionRepresentation extends MappingRepresentation { private final Map<String, EntityExtensionRepresentation> extended; public ServerExtensionRepresentation( String name, List<ExtensionPointRepresentation> methods ) { super( RepresentationType.SERVER_PLUGIN_DESCRIPTION ); this.extended = new HashMap<String, EntityExtensionRepresentation>(); for ( ExtensionPointRepresentation extension : methods ) { EntityExtensionRepresentation entity = extended.get( extension.getExtendedEntity() ); if ( entity == null ) { extended.put( extension.getExtendedEntity(), entity = new EntityExtensionRepresentation() ); } entity.add( extension ); } } @Override protected void serialize( MappingSerializer serializer ) { for ( Map.Entry<String, EntityExtensionRepresentation> entity : extended.entrySet() ) { serializer.putMapping( entity.getKey(), entity.getValue() ); } } private static class EntityExtensionRepresentation extends MappingRepresentation { private final List<ExtensionPointRepresentation> extensions; EntityExtensionRepresentation() { super( "entity-extensions" ); this.extensions = new ArrayList<ExtensionPointRepresentation>(); } void add( ExtensionPointRepresentation extension ) { extensions.add( extension ); } @Override protected void serialize( MappingSerializer serializer ) { for ( ExtensionPointRepresentation extension : extensions ) { serializer.putMapping( extension.getName(), extension ); } } } }
false
community_server_src_main_java_org_neo4j_server_rest_repr_ServerExtensionRepresentation.java
2,918
Serializer serializer = new Serializer(URI.create( baseUrl ), null){};
false
community_server-api_src_test_java_org_neo4j_server_rest_repr_SerializerTest.java
2,919
public class SerializerTest { @Test public void shouldPrependBaseUriToRelativePaths() { String baseUrl = "http://baseurl/"; Serializer serializer = new Serializer(URI.create( baseUrl ), null){}; String aRelativeUrl = "/path/path/path"; assertThat(serializer.relativeUri( aRelativeUrl ), is( baseUrl + aRelativeUrl.substring( 1 ) )); assertThat(serializer.relativeTemplate( aRelativeUrl ), is( baseUrl + aRelativeUrl.substring( 1 ) )); } }
false
community_server-api_src_test_java_org_neo4j_server_rest_repr_SerializerTest.java
2,920
abstract class Serializer { private final URI baseUri; private final ExtensionInjector extensions; Serializer( URI baseUri, ExtensionInjector extensions ) { this.baseUri = baseUri; this.extensions = extensions; } final void serialize( MappingWriter mapping, MappingRepresentation value ) { injectExtensions( mapping, value, baseUri, extensions ); value.serialize( new MappingSerializer( mapping, baseUri, extensions ) ); mapping.done(); } static void injectExtensions( MappingWriter mapping, MappingRepresentation value, URI baseUri, ExtensionInjector injector ) { if ( value instanceof ExtensibleRepresentation && injector != null ) { Map<String/*name*/, List<String/*method*/>> extData = injector.getExensionsFor( value.type.extend ); String entityIdentity = ( (ExtensibleRepresentation) value ).getIdentity(); if ( extData != null ) { MappingWriter extensions = mapping.newMapping( RepresentationType.PLUGINS, "extensions" ); for ( Map.Entry<String, List<String>> ext : extData.entrySet() ) { MappingWriter extension = extensions.newMapping( RepresentationType.PLUGIN, ext.getKey() ); for ( String method : ext.getValue() ) { StringBuilder path = new StringBuilder( "/ext/" ).append( ext.getKey() ); path.append( "/" ).append( value.type.valueName ); if ( entityIdentity != null ) path.append( "/" ).append( entityIdentity ); path.append( "/" ).append( method ); extension.writeValue( RepresentationType.URI, method, joinBaseWithRelativePath( baseUri, path.toString() ) ); } extension.done(); } extensions.done(); } } } final void serialize( ListWriter list, ListRepresentation value ) { value.serialize( new ListSerializer( list, baseUri, extensions ) ); list.done(); } final String relativeUri(String path) { return joinBaseWithRelativePath(baseUri, path); } final String relativeTemplate( String path ) { return joinBaseWithRelativePath( baseUri, path ); } static String joinBaseWithRelativePath( URI baseUri, String path ) { String base = baseUri.toString(); final StringBuilder result = new StringBuilder(base.length() + path.length() +1).append(base); if ( base.endsWith( "/" ) ) { if ( path.startsWith( "/" ) ) { return result.append(path.substring(1)).toString(); } } else if ( !path.startsWith( "/" ) ) { return result.append('/').append(path).toString(); } return result.append(path).toString(); } protected void checkThatItIsBuiltInType( Object value ) { if ( !"java.lang".equals( value.getClass().getPackage().getName() ) ) { throw new IllegalArgumentException( "Unsupported number type: " + value.getClass() ); } } }
false
community_server-api_src_main_java_org_neo4j_server_rest_repr_Serializer.java
2,921
public final class ScoredRelationshipRepresentation extends ScoredEntityRepresentation<RelationshipRepresentation> { public ScoredRelationshipRepresentation( RelationshipRepresentation delegate, float score ) { super( delegate, score ); } @Override public String getIdentity() { return getDelegate().getIdentity(); } @Mapping( "type" ) public ValueRepresentation getType() { return getDelegate().getType(); } @Mapping( "start" ) public ValueRepresentation startNodeUri() { return getDelegate().startNodeUri(); } @Mapping( "end" ) public ValueRepresentation endNodeUri() { return getDelegate().endNodeUri(); } @Mapping( "properties" ) public ValueRepresentation propertiesUri() { return getDelegate().propertiesUri(); } @Mapping( "property" ) public ValueRepresentation propertyUriTemplate() { return getDelegate().propertyUriTemplate(); } }
false
community_server_src_main_java_org_neo4j_server_rest_repr_ScoredRelationshipRepresentation.java
2,922
public final class ScoredNodeRepresentation extends ScoredEntityRepresentation<NodeRepresentation> { public ScoredNodeRepresentation( NodeRepresentation delegate, float score ) { super( delegate, score ); } @Mapping( "create_relationship" ) public ValueRepresentation relationshipCreationUri() { return getDelegate().relationshipCreationUri(); } @Mapping( "all_relationships" ) public ValueRepresentation allRelationshipsUri() { return getDelegate().allRelationshipsUri(); } @Mapping( "incoming_relationships" ) public ValueRepresentation incomingRelationshipsUri() { return getDelegate().incomingRelationshipsUri(); } @Mapping( "outgoing_relationships" ) public ValueRepresentation outgoingRelationshipsUri() { return getDelegate().outgoingRelationshipsUri(); } @Mapping( "all_typed_relationships" ) public ValueRepresentation allTypedRelationshipsUriTemplate() { return getDelegate().allTypedRelationshipsUriTemplate(); } @Mapping( "incoming_typed_relationships" ) public ValueRepresentation incomingTypedRelationshipsUriTemplate() { return getDelegate().incomingTypedRelationshipsUriTemplate(); } @Mapping( "outgoing_typed_relationships" ) public ValueRepresentation outgoingTypedRelationshipsUriTemplate() { return getDelegate().outgoingTypedRelationshipsUriTemplate(); } @Mapping( "properties" ) public ValueRepresentation propertiesUri() { return getDelegate().propertiesUri(); } @Mapping( "labels" ) public ValueRepresentation labelsUriTemplate() { return getDelegate().labelsUriTemplate(); } @Mapping( "property" ) public ValueRepresentation propertyUriTemplate() { return getDelegate().propertyUriTemplate(); } @Mapping( "traverse" ) public ValueRepresentation traverseUriTemplate() { return getDelegate().traverseUriTemplate(); } @Mapping( "paged_traverse" ) public ValueRepresentation pagedTraverseUriTemplate() { return getDelegate().pagedTraverseUriTemplate(); } }
false
community_server_src_main_java_org_neo4j_server_rest_repr_ScoredNodeRepresentation.java
2,923
public abstract class ScoredEntityRepresentation<E extends ObjectRepresentation & ExtensibleRepresentation & EntityRepresentation> extends ObjectRepresentation implements ExtensibleRepresentation, EntityRepresentation { private final E delegate; private final float score; protected ScoredEntityRepresentation( E scoredObject, float score ) { super( scoredObject.type ); this.delegate = scoredObject; this.score = score; } protected E getDelegate() { return delegate; } @Override public String getIdentity() { return getDelegate().getIdentity(); } @Override @Mapping( "self" ) public ValueRepresentation selfUri() { return delegate.selfUri(); } @Mapping( "score" ) public ValueRepresentation score() { return ValueRepresentation.number( score ); } @Override void extraData( MappingSerializer serializer ) { delegate.extraData( serializer ); } }
false
community_server_src_main_java_org_neo4j_server_rest_repr_ScoredEntityRepresentation.java
2,924
public final class PropertiesRepresentation extends MappingRepresentation { private final PropertyContainer entity; public PropertiesRepresentation( PropertyContainer entity ) { super( RepresentationType.PROPERTIES ); this.entity = entity; } public boolean isEmpty() { return !entity.getPropertyKeys() .iterator() .hasNext(); } @Override protected void serialize( MappingSerializer serializer ) { serialize( serializer.writer ); } void serialize( MappingWriter writer ) { PropertyTypeDispatcher.consumeProperties( new Consumer( writer ), entity ); } private static class Consumer extends PropertyTypeDispatcher<String, Void> { private final MappingWriter writer; Consumer( MappingWriter serializer ) { this.writer = serializer; } @Override protected Void dispatchBooleanProperty( boolean property, String param ) { writer.writeBoolean( param, property ); return null; } @Override protected Void dispatchByteProperty( byte property, String param ) { writer.writeInteger( RepresentationType.BYTE, param, property ); return null; } @Override protected Void dispatchCharacterProperty( char property, String param ) { writer.writeInteger( RepresentationType.CHAR, param, property ); return null; } @Override protected Void dispatchDoubleProperty( double property, String param ) { writer.writeFloatingPointNumber( RepresentationType.DOUBLE, param, property ); return null; } @Override protected Void dispatchFloatProperty( float property, String param ) { writer.writeFloatingPointNumber( RepresentationType.FLOAT, param, property ); return null; } @Override protected Void dispatchIntegerProperty( int property, String param ) { writer.writeInteger( RepresentationType.INTEGER, param, property ); return null; } @Override protected Void dispatchLongProperty( long property, String param ) { writer.writeInteger( RepresentationType.LONG, param, property ); return null; } @Override protected Void dispatchShortProperty( short property, String param ) { writer.writeInteger( RepresentationType.SHORT, param, property ); return null; } @Override protected Void dispatchStringProperty( String property, String param ) { writer.writeString( param, property ); return null; } @Override protected Void dispatchStringArrayProperty( String[] property, String param ) { ListWriter list = writer.newList( RepresentationType.STRING, param ); for ( String s : property ) { list.writeString( s ); } list.done(); return null; } @Override @SuppressWarnings( "boxing" ) protected Void dispatchByteArrayProperty( PropertyArray<byte[], Byte> array, String param ) { ListWriter list = writer.newList( RepresentationType.BYTE, param ); for ( Byte b : array ) { list.writeInteger( RepresentationType.BYTE, b ); } list.done(); return null; } @Override @SuppressWarnings( "boxing" ) protected Void dispatchShortArrayProperty( PropertyArray<short[], Short> array, String param ) { ListWriter list = writer.newList( RepresentationType.SHORT, param ); for ( Short s : array ) { list.writeInteger( RepresentationType.SHORT, s ); } list.done(); return null; } @Override @SuppressWarnings( "boxing" ) protected Void dispatchCharacterArrayProperty( PropertyArray<char[], Character> array, String param ) { ListWriter list = writer.newList( RepresentationType.CHAR, param ); for ( Character c : array ) { list.writeInteger( RepresentationType.CHAR, c ); } list.done(); return null; } @Override @SuppressWarnings( "boxing" ) protected Void dispatchIntegerArrayProperty( PropertyArray<int[], Integer> array, String param ) { ListWriter list = writer.newList( RepresentationType.INTEGER, param ); for ( Integer i : array ) { list.writeInteger( RepresentationType.INTEGER, i ); } list.done(); return null; } @Override @SuppressWarnings( "boxing" ) protected Void dispatchLongArrayProperty( PropertyArray<long[], Long> array, String param ) { ListWriter list = writer.newList( RepresentationType.LONG, param ); for ( Long j : array ) { list.writeInteger( RepresentationType.LONG, j ); } list.done(); return null; } @Override @SuppressWarnings( "boxing" ) protected Void dispatchFloatArrayProperty( PropertyArray<float[], Float> array, String param ) { ListWriter list = writer.newList( RepresentationType.FLOAT, param ); for ( Float f : array ) { list.writeFloatingPointNumber( RepresentationType.FLOAT, f ); } list.done(); return null; } @Override @SuppressWarnings( "boxing" ) protected Void dispatchDoubleArrayProperty( PropertyArray<double[], Double> array, String param ) { ListWriter list = writer.newList( RepresentationType.DOUBLE, param ); for ( Double d : array ) { list.writeFloatingPointNumber( RepresentationType.DOUBLE, d ); } list.done(); return null; } @Override @SuppressWarnings( "boxing" ) protected Void dispatchBooleanArrayProperty( PropertyArray<boolean[], Boolean> array, String param ) { ListWriter list = writer.newList( RepresentationType.BOOLEAN, param ); for ( Boolean z : array ) { list.writeBoolean( z ); } list.done(); return null; } } public static Representation value( Object property ) { return ValueRepresentation.property( property ); } }
false
community_server_src_main_java_org_neo4j_server_rest_repr_PropertiesRepresentation.java
2,925
{ @Override protected Representation underlyingObjectToObject( Relationship node ) { return ValueRepresentation.uri( RelationshipRepresentation.path( node ) ); } } );
false
community_server_src_main_java_org_neo4j_server_rest_repr_PathRepresentation.java
2,926
{ @Override protected Representation underlyingObjectToObject( Node node ) { return ValueRepresentation.uri( NodeRepresentation.path( node ) ); } } );
false
community_server_src_main_java_org_neo4j_server_rest_repr_PathRepresentation.java
2,927
public class PathRepresentation<P extends Path> extends ObjectRepresentation // implements // ExtensibleRepresentation { private final P path; public PathRepresentation( P path ) { super( RepresentationType.PATH ); this.path = path; } /* @Override public String getIdentity() { StringBuilder result = new StringBuilder( Long.toString( path.startNode().getId() ) ); String sep = "+"; for ( Relationship rel : path.relationships() ) { result.append( sep ).append( Long.toString( rel.getId() ) ); sep = "-"; } result.append( "+" ).append( Long.toString( path.endNode().getId() ) ); return result.toString(); } */ protected P getPath() { return path; } @Mapping( "start" ) public ValueRepresentation startNode() { return ValueRepresentation.uri( NodeRepresentation.path( path.startNode() ) ); } @Mapping( "end" ) public ValueRepresentation endNode() { return ValueRepresentation.uri( NodeRepresentation.path( path.endNode() ) ); } @Mapping( "length" ) public ValueRepresentation length() { return ValueRepresentation.number( path.length() ); } @Mapping( "nodes" ) public ListRepresentation nodes() { return new ListRepresentation( RepresentationType.NODE, new IterableWrapper<Representation, Node>( path.nodes() ) { @Override protected Representation underlyingObjectToObject( Node node ) { return ValueRepresentation.uri( NodeRepresentation.path( node ) ); } } ); } @Mapping( "relationships" ) public ListRepresentation relationships() { return new ListRepresentation( RepresentationType.RELATIONSHIP, new IterableWrapper<Representation, Relationship>( path.relationships() ) { @Override protected Representation underlyingObjectToObject( Relationship node ) { return ValueRepresentation.uri( RelationshipRepresentation.path( node ) ); } } ); } }
false
community_server_src_main_java_org_neo4j_server_rest_repr_PathRepresentation.java
2,928
public class MapRepresentationTest { @Test public void shouldSerializeMapWithSimpleTypes() throws Exception { MapRepresentation rep = new MapRepresentation( map( "nulls", null, "strings", "a string", "numbers", 42, "booleans", true ) ); OutputFormat format = new OutputFormat( new JsonFormat(), new URI( "http://localhost/" ), null ); String serializedMap = format.assemble( rep ); Map<String, Object> map = JsonHelper.jsonToMap( serializedMap ); assertThat( map.get( "nulls" ), is( nullValue() ) ); assertThat( (String) map.get( "strings" ), is( "a string" ) ); assertThat( (Integer) map.get( "numbers" ), is( 42 ) ); assertThat( (Boolean) map.get( "booleans" ), is( true ) ); } @Test @SuppressWarnings("unchecked") public void shouldSerializeMapWithArrayTypes() throws Exception { MapRepresentation rep = new MapRepresentation( map( "strings", new String[]{"a string", "another string"}, "numbers", new int[]{42, 87}, "booleans", new boolean[]{true, false}, "Booleans", new Boolean[]{TRUE, FALSE} ) ); OutputFormat format = new OutputFormat( new JsonFormat(), new URI( "http://localhost/" ), null ); String serializedMap = format.assemble( rep ); Map<String, Object> map = JsonHelper.jsonToMap( serializedMap ); assertThat( (List<String>) map.get( "strings" ), is( asList( "a string", "another string" ) ) ); assertThat( (List<Integer>) map.get( "numbers" ), is( asList( 42, 87 ) ) ); assertThat( (List<Boolean>) map.get( "booleans" ), is( asList( true, false ) ) ); assertThat( (List<Boolean>) map.get( "Booleans" ), is( asList( true, false ) ) ); } @Test @SuppressWarnings("unchecked") public void shouldSerializeMapWithListsOfSimpleTypes() throws Exception { MapRepresentation rep = new MapRepresentation( map( "lists of nulls", asList( null, null ), "lists of strings", asList( "a string", "another string" ), "lists of numbers", asList( 23, 87, 42 ), "lists of booleans", asList( true, false, true ) ) ); OutputFormat format = new OutputFormat( new JsonFormat(), new URI( "http://localhost/" ), null ); String serializedMap = format.assemble( rep ); Map<String, Object> map = JsonHelper.jsonToMap( serializedMap ); assertThat( (List<Object>) map.get( "lists of nulls" ), is( asList( null, null ) ) ); assertThat( (List<String>) map.get( "lists of strings" ), is( asList( "a string", "another string" ) ) ); assertThat( (List<Integer>) map.get( "lists of numbers" ), is( asList( 23, 87, 42 ) ) ); assertThat( (List<Boolean>) map.get( "lists of booleans" ), is( asList( true, false, true ) ) ); } @Test public void shouldSerializeMapWithMapsOfSimpleTypes() throws Exception { MapRepresentation rep = new MapRepresentation( map( "maps with nulls", map( "nulls", null ), "maps with strings", map( "strings", "a string" ), "maps with numbers", map( "numbers", 42 ), "maps with booleans", map( "booleans", true ) ) ); OutputFormat format = new OutputFormat( new JsonFormat(), new URI( "http://localhost/" ), null ); String serializedMap = format.assemble( rep ); Map<String, Object> map = JsonHelper.jsonToMap( serializedMap ); assertThat( ((Map) map.get( "maps with nulls" )).get( "nulls" ), is( nullValue() ) ); assertThat( (String) ((Map) map.get( "maps with strings" )).get( "strings" ), is( "a string" ) ); assertThat( (Integer) ((Map) map.get( "maps with numbers" )).get( "numbers" ), is( 42 ) ); assertThat( (Boolean) ((Map) map.get( "maps with booleans" )).get( "booleans" ), is( true ) ); } @Test @SuppressWarnings("unchecked") public void shouldSerializeArbitrarilyNestedMapsAndLists() throws Exception { MapRepresentation rep = new MapRepresentation( map( "a map with a list in it", map( "a list", asList( 42, 87 ) ), "a list with a map in it", asList( map( "foo", "bar", "baz", false ) ) ) ); OutputFormat format = new OutputFormat( new JsonFormat(), new URI( "http://localhost/" ), null ); String serializedMap = format.assemble( rep ); Map<String, Object> map = JsonHelper.jsonToMap( serializedMap ); assertThat( (List<Integer>) ((Map) map.get( "a map with a list in it" )).get( "a list" ), is( asList( 42, 87 ) ) ); assertThat( (String) ((Map) ((List) map.get( "a list with a map in it" )).get( 0 )).get( "foo" ), is( "bar" ) ); assertThat( (Boolean) ((Map) ((List) map.get( "a list with a map in it" )).get( 0 )).get( "baz" ), is( false ) ); } }
false
community_server_src_test_java_org_neo4j_server_rest_repr_MapRepresentationTest.java
2,929
public class MapRepresentation extends MappingRepresentation { private final Map value; public MapRepresentation( Map value ) { super( RepresentationType.MAP ); this.value = value; } @Override protected void serialize( MappingSerializer serializer ) { for ( Object key : value.keySet() ) { Object val = value.get( key ); if ( val instanceof Number ) { serializer.putNumber( key.toString(), (Number) val ); } else if ( val instanceof Boolean ) { serializer.putBoolean( key.toString(), (Boolean) val ); } else if ( val instanceof String ) { serializer.putString( key.toString(), (String) val ); } else if (val instanceof Path ) { PathRepresentation<Path> representation = new PathRepresentation<>( (Path) val ); serializer.putMapping( key.toString(), representation ); } else if ( val instanceof Iterable ) { serializer.putList( key.toString(), ObjectToRepresentationConverter.getListRepresentation( (Iterable) val ) ); } else if ( val instanceof Map ) { serializer.putMapping( key.toString(), ObjectToRepresentationConverter.getMapRepresentation( (Map) val ) ); } else if (val == null) { serializer.putString( key.toString(), null ); } else if (val.getClass().isArray()) { Object[] objects = toArray( val ); serializer.putList( key.toString(), ObjectToRepresentationConverter.getListRepresentation( asList(objects) ) ); } else if (val instanceof Node || val instanceof Relationship ) { Representation representation = ObjectToRepresentationConverter.getSingleRepresentation( val ); serializer.putMapping( key.toString(), (MappingRepresentation) representation ); } else { throw new IllegalArgumentException( "Unsupported value type: " + val.getClass() ); } } } private Object[] toArray( Object val ) { int length = getLength( val ); Object[] objects = new Object[length]; for (int i=0; i<length; i++) { objects[i] = get( val, i ); } return objects; } }
false
community_server_src_main_java_org_neo4j_server_rest_repr_MapRepresentation.java
2,930
public abstract class ListWriter { MappingWriter newMapping( RepresentationType type ) { return newMapping( type.valueName ); } protected abstract MappingWriter newMapping( String type ); ListWriter newList( RepresentationType type ) { if ( type.listName == null ) throw new IllegalStateException( "Invalid list type: " + type ); return newList( type.listName ); } protected abstract ListWriter newList( String type ); protected void writeString( String value ) { writeValue( RepresentationType.STRING, value ); } @SuppressWarnings( "boxing" ) protected void writeBoolean( boolean value ) { writeValue( RepresentationType.BOOLEAN, value ); } void writeInteger( RepresentationType type, long value ) { writeInteger( type.valueName, value ); } @SuppressWarnings( "boxing" ) protected void writeInteger( String type, long value ) { writeValue( type, value ); } void writeFloatingPointNumber( RepresentationType type, double value ) { writeFloatingPointNumber( type.valueName, value ); } @SuppressWarnings( "boxing" ) protected void writeFloatingPointNumber( String type, double value ) { writeValue( type, value ); } void writeValue( RepresentationType type, Object value ) { writeValue( type.valueName, value ); } protected abstract void writeValue( String type, Object value ); protected abstract void done(); }
false
community_server-api_src_main_java_org_neo4j_server_rest_repr_ListWriter.java
2,931
public class ListSerializer extends Serializer { final ListWriter writer; ListSerializer( ListWriter writer, URI baseUri, ExtensionInjector extensions ) { super( baseUri, extensions ); this.writer = writer; } public void addUri( String path ) { writer.writeValue( RepresentationType.URI, relativeUri( path ) ); } public void addUriTemplate( String template ) { writer.writeValue( RepresentationType.TEMPLATE, relativeTemplate( template ) ); } public void addString( String value ) { writer.writeString( value ); } public void addMapping( MappingRepresentation value ) { serialize( writer.newMapping( value.type ), value ); } public void addList( ListRepresentation value ) { serialize( writer.newList( value.type ), value ); } public final void addNumber( Number value ) { if ( value instanceof Double || value instanceof Float ) { writer.writeFloatingPointNumber( RepresentationType.valueOf( value.getClass() ), value.doubleValue() ); } else { checkThatItIsBuiltInType( value ); writer.writeInteger( RepresentationType.valueOf( value.getClass() ), value.longValue() ); } } }
false
community_server-api_src_main_java_org_neo4j_server_rest_repr_ListSerializer.java
2,932
{ int pos = 0; @Override protected ValueRepresentation fetchNextOrNull() { if ( pos >= values.length ) return null; return ValueRepresentation.number( values[pos++] ); } };
false
community_server-api_src_main_java_org_neo4j_server_rest_repr_ListRepresentation.java
2,933
{ @Override public Iterator<ValueRepresentation> iterator() { return new PrefetchingIterator<ValueRepresentation>() { int pos = 0; @Override protected ValueRepresentation fetchNextOrNull() { if ( pos >= values.length ) return null; return ValueRepresentation.number( values[pos++] ); } }; } } );
false
community_server-api_src_main_java_org_neo4j_server_rest_repr_ListRepresentation.java
2,934
{ int pos = 0; @Override protected ValueRepresentation fetchNextOrNull() { if ( pos >= values.length ) return null; return ValueRepresentation.number( values[pos++] ); } };
false
community_server-api_src_main_java_org_neo4j_server_rest_repr_ListRepresentation.java
2,935
{ @Override public Iterator<ValueRepresentation> iterator() { return new PrefetchingIterator<ValueRepresentation>() { int pos = 0; @Override protected ValueRepresentation fetchNextOrNull() { if ( pos >= values.length ) return null; return ValueRepresentation.number( values[pos++] ); } }; } } );
false
community_server-api_src_main_java_org_neo4j_server_rest_repr_ListRepresentation.java
2,936
{ @Override protected Representation underlyingObjectToObject( RelationshipType value ) { return ValueRepresentation.relationshipType( value ); } } );
false
community_server-api_src_main_java_org_neo4j_server_rest_repr_ListRepresentation.java
2,937
{ @Override protected Representation underlyingObjectToObject( String value ) { return ValueRepresentation.string( value ); } } );
false
community_server-api_src_main_java_org_neo4j_server_rest_repr_ListRepresentation.java
2,938
public class ListRepresentation extends Representation { protected final Iterable<? extends Representation> content; public ListRepresentation( final String type, final Iterable<? extends Representation> content ) { super( type ); this.content = content; } public ListRepresentation( RepresentationType type, final Iterable<? extends Representation> content ) { super( type ); this.content = content; } @Override String serialize( RepresentationFormat format, URI baseUri, ExtensionInjector extensions ) { ListWriter writer = format.serializeList( type ); serialize( new ListSerializer( writer, baseUri, extensions ) ); writer.done(); return format.complete( writer ); } void serialize( ListSerializer serializer ) { Iterator<? extends Representation> contentIterator = content.iterator(); try { while ( contentIterator.hasNext() ) { Representation repr = contentIterator.next(); repr.addTo( serializer ); } } finally { // Make sure we exhaust this iterator in case it has an internal close mechanism while (contentIterator.hasNext()) contentIterator.next(); } } @Override void addTo( ListSerializer serializer ) { serializer.addList( this ); } @Override void putTo( MappingSerializer serializer, String key ) { serializer.putList( key, this ); } public static ListRepresentation strings( String... values ) { return string( Arrays.asList( values ) ); } public static ListRepresentation string( Iterable<String> values ) { return new ListRepresentation( RepresentationType.STRING, new IterableWrapper<Representation, String>( values ) { @Override protected Representation underlyingObjectToObject( String value ) { return ValueRepresentation.string( value ); } } ); } public static ListRepresentation relationshipTypes( Iterable<RelationshipType> types ) { return new ListRepresentation( RepresentationType.RELATIONSHIP_TYPE, new IterableWrapper<Representation, RelationshipType>( types ) { @Override protected Representation underlyingObjectToObject( RelationshipType value ) { return ValueRepresentation.relationshipType( value ); } } ); } public static ListRepresentation numbers( final long... values ) { return new ListRepresentation( RepresentationType.LONG, new Iterable<ValueRepresentation>() { @Override public Iterator<ValueRepresentation> iterator() { return new PrefetchingIterator<ValueRepresentation>() { int pos = 0; @Override protected ValueRepresentation fetchNextOrNull() { if ( pos >= values.length ) return null; return ValueRepresentation.number( values[pos++] ); } }; } } ); } public static ListRepresentation numbers( final double[] values ) { return new ListRepresentation( RepresentationType.DOUBLE, new Iterable<ValueRepresentation>() { @Override public Iterator<ValueRepresentation> iterator() { return new PrefetchingIterator<ValueRepresentation>() { int pos = 0; @Override protected ValueRepresentation fetchNextOrNull() { if ( pos >= values.length ) return null; return ValueRepresentation.number( values[pos++] ); } }; } } ); } }
false
community_server-api_src_main_java_org_neo4j_server_rest_repr_ListRepresentation.java
2,939
public class ListEntityRepresentation extends Representation implements EntityRepresentation { private ListRepresentation listRepresentation; private URI selfUfi; public ListEntityRepresentation( ListRepresentation listRepresentation, URI selfUfi ) { super( "list" ); this.listRepresentation = listRepresentation; this.selfUfi = selfUfi; } @Override public ValueRepresentation selfUri() { return ValueRepresentation.uri( selfUfi.getPath() ); } @Override String serialize( RepresentationFormat format, URI baseUri, ExtensionInjector extensions ) { return listRepresentation.serialize( format, baseUri, extensions ); } @Override void addTo( ListSerializer serializer ) { listRepresentation.addTo( serializer ); } @Override void putTo( MappingSerializer serializer, String key ) { listRepresentation.putTo( serializer, key ); } }
false
community_server_src_main_java_org_neo4j_server_rest_repr_ListEntityRepresentation.java
2,940
@Provider public final class InputFormatProvider extends InjectableProvider<InputFormat> { private final RepresentationFormatRepository repository; public InputFormatProvider( RepresentationFormatRepository repository ) { super( InputFormat.class ); this.repository = repository; } @Override public InputFormat getValue( HttpContext context ) { try { return repository.inputFormat( context.getRequest() .getMediaType() ); } catch ( MediaTypeNotSupportedException e ) { throw new WebApplicationException( Response.status( Status.UNSUPPORTED_MEDIA_TYPE ) .entity( e.getMessage() ) .build() ); } } }
false
community_server_src_main_java_org_neo4j_server_rest_repr_InputFormatProvider.java
2,941
public final class IndexedEntityRepresentation extends MappingRepresentation implements ExtensibleRepresentation, EntityRepresentation { private final MappingRepresentation entity; private final ValueRepresentation selfUri; @SuppressWarnings( "boxing" ) public IndexedEntityRepresentation( Node node, String key, String value, IndexRepresentation indexRepresentation ) { this( new NodeRepresentation( node ), node.getId(), key, value, indexRepresentation ); } @SuppressWarnings( "boxing" ) public IndexedEntityRepresentation( Relationship rel, String key, String value, IndexRepresentation indexRepresentation ) { this( new RelationshipRepresentation( rel ), rel.getId(), key, value, indexRepresentation ); } private IndexedEntityRepresentation( MappingRepresentation entity, long entityId, String key, String value, IndexRepresentation indexRepresentation ) { super( entity.type ); this.entity = entity; selfUri = ValueRepresentation.uri( indexRepresentation.relativeUriFor( key, value, entityId ) ); } @Override public String getIdentity() { return ( (ExtensibleRepresentation) entity ).getIdentity(); } public ValueRepresentation selfUri() { return selfUri; } @Override protected void serialize( MappingSerializer serializer ) { entity.serialize( serializer ); selfUri().putTo( serializer, "indexed" ); } }
false
community_server_src_main_java_org_neo4j_server_rest_repr_IndexedEntityRepresentation.java
2,942
public abstract class IndexRepresentation extends MappingRepresentation implements EntityRepresentation { private final String name; private final Map<String, String> type; public IndexRepresentation( String name, Map<String, String> type ) { super( RepresentationType.INDEX ); this.name = name; this.type = type; } @Override protected void serialize( final MappingSerializer serializer ) { serializer.putUriTemplate( "template", path() + "{key}/{value}" ); for ( Map.Entry<String, String> pair : type.entrySet() ) { serializer.putString( pair.getKey(), pair.getValue() ); } } public String relativeUriFor( String key, String value, long entityId ) { return path() + URIHelper.encode( key ) + "/" + URIHelper.encode( value ) + "/" + Long.toString( entityId ); } @Override public ValueRepresentation selfUri() { return ValueRepresentation.uri( path() ); } protected String path() { return "index/" + propertyContainerType() + "/" + URIHelper.encode(name) + "/"; } protected abstract String propertyContainerType(); }
false
community_server_src_main_java_org_neo4j_server_rest_repr_IndexRepresentation.java
2,943
{ @Override public Representation apply( String propertyKey ) { return ValueRepresentation.string( propertyKey ); } };
false
community_server_src_main_java_org_neo4j_server_rest_repr_IndexDefinitionRepresentation.java
2,944
public class IndexDefinitionRepresentation extends MappingRepresentation { private final IndexDefinition indexDefinition; public IndexDefinitionRepresentation( IndexDefinition indexDefinition ) { super( RepresentationType.INDEX_DEFINITION ); this.indexDefinition = indexDefinition; } @Override protected void serialize( MappingSerializer serializer ) { serializer.putString( "label", indexDefinition.getLabel().name() ); Function<String, Representation> converter = new Function<String, Representation>() { @Override public Representation apply( String propertyKey ) { return ValueRepresentation.string( propertyKey ); } }; Iterable<Representation> propertyKeyRepresentations = map( converter, indexDefinition.getPropertyKeys() ); serializer.putList( "property_keys", new ListRepresentation( RepresentationType.STRING, propertyKeyRepresentations ) ); } }
false
community_server_src_main_java_org_neo4j_server_rest_repr_IndexDefinitionRepresentation.java
2,945
public class FullPathRepresentation extends ObjectRepresentation { private final Path path; public FullPathRepresentation( Path path ) { super( RepresentationType.FULL_PATH ); this.path = path; } @Mapping( "start" ) public NodeRepresentation startNode() { return new NodeRepresentation( path.startNode() ); } @Mapping( "end" ) public NodeRepresentation endNode() { return new NodeRepresentation( path.endNode() ); } @Mapping( "length" ) public ValueRepresentation length() { return ValueRepresentation.number( path.length() ); } @Mapping( "nodes" ) public ListRepresentation nodes() { return NodeRepresentation.list( path.nodes() ); } @Mapping( "relationships" ) public ListRepresentation relationships() { return RelationshipRepresentation.list( path.relationships() ); } }
false
community_server_src_main_java_org_neo4j_server_rest_repr_FullPathRepresentation.java
2,946
public class FullPath { private final Path path; public FullPath(Path path) { this.path = path; } public Path getPath() { return path; } }
false
community_server-api_src_main_java_org_neo4j_server_rest_repr_FullPath.java
2,947
public abstract class MappingRepresentation extends Representation { MappingRepresentation( RepresentationType type ) { super( type ); } public MappingRepresentation( String type ) { super( type ); } @Override String serialize( RepresentationFormat format, URI baseUri, ExtensionInjector extensions ) { MappingWriter writer = format.serializeMapping( type ); Serializer.injectExtensions( writer, this, baseUri, extensions ); serialize( new MappingSerializer( writer, baseUri, extensions ) ); writer.done(); return format.complete( writer ); } protected abstract void serialize( MappingSerializer serializer ); @Override void addTo( ListSerializer serializer ) { serializer.addMapping( this ); } @Override void putTo( MappingSerializer serializer, String key ) { serializer.putMapping( key, this ); } }
false
community_server-api_src_main_java_org_neo4j_server_rest_repr_MappingRepresentation.java
2,948
public class MappingSerializer extends Serializer { final MappingWriter writer; MappingSerializer( MappingWriter writer, URI baseUri, ExtensionInjector extensions ) { super( baseUri, extensions ); this.writer = writer; } public void putUri( String key, String path ) { writer.writeValue( RepresentationType.URI, key, relativeUri( path ) ); } public void putUriTemplate( String key, String template ) { writer.writeValue( RepresentationType.TEMPLATE, key, relativeTemplate( template ) ); } public void putString( String key, String value ) { writer.writeString( key, value ); } public void putBoolean( String key, boolean value ) { writer.writeBoolean( key, value ); } public void putMapping( String key, MappingRepresentation value ) { serialize( writer.newMapping( value.type, key ), value ); } public void putList( String key, ListRepresentation value ) { serialize( writer.newList( value.type, key ), value ); } public final void putNumber( String key, Number value ) { if ( value instanceof Double || value instanceof Float ) { writer.writeFloatingPointNumber( RepresentationType.valueOf( value.getClass() ), key, value.doubleValue() ); } else { checkThatItIsBuiltInType( value ); writer.writeInteger( RepresentationType.valueOf( value.getClass() ), key, value.longValue() ); } } }
false
community_server-api_src_main_java_org_neo4j_server_rest_repr_MappingSerializer.java
2,949
public abstract class MappingWriter { MappingWriter newMapping( RepresentationType type, String param ) { return newMapping( type.valueName, param ); } protected boolean isInteractive() { return false; } protected abstract MappingWriter newMapping( String type, String key ); ListWriter newList( RepresentationType type, String param ) { if ( type.valueName == "map" ) { return newList( type.listName, param ); } if ( type.listName == null ) { throw new IllegalStateException( "Invalid list type: " + type ); } return newList( type.listName, param ); } protected abstract ListWriter newList( String type, String key ); protected void writeString( String key, String value ) { writeValue( RepresentationType.STRING, key, value ); } void writeInteger( RepresentationType type, String param, long property ) { writeInteger( type.valueName, param, property ); } @SuppressWarnings( "boxing" ) protected void writeInteger( String type, String key, long value ) { writeValue( type, key, value ); } void writeFloatingPointNumber( RepresentationType type, String key, double value ) { writeFloatingPointNumber( type.valueName, key, value ); } @SuppressWarnings( "boxing" ) protected void writeFloatingPointNumber( String type, String key, double value ) { writeValue( type, key, value ); } @SuppressWarnings( "boxing" ) protected void writeBoolean( String key, boolean value ) { writeValue( RepresentationType.BOOLEAN, key, value ); } void writeValue( RepresentationType type, String key, Object value ) { writeValue( type.valueName, key, value ); } protected abstract void writeValue( String type, String key, Object value ); protected abstract void done(); }
false
community_server-api_src_main_java_org_neo4j_server_rest_repr_MappingWriter.java
2,950
public class ObjectToRepresentationConverter { public static Representation convert( final Object data ) { if ( data instanceof Iterable ) { return getListRepresentation( (Iterable) data ); } if ( data instanceof Iterator ) { Iterator iterator = (Iterator) data; return getIteratorRepresentation( iterator ); } if ( data instanceof Map ) { return getMapRepresentation( (Map) data ); } return getSingleRepresentation( data ); } public static MappingRepresentation getMapRepresentation( Map data ) { return new MapRepresentation( data ); } @SuppressWarnings("unchecked") static Representation getIteratorRepresentation( Iterator data ) { final FirstItemIterable<Representation> results = new FirstItemIterable<>(new IteratorWrapper<Representation, Object>(data) { @Override protected Representation underlyingObjectToObject(Object value) { if ( value instanceof Iterable ) { FirstItemIterable<Representation> nested = convertValuesToRepresentations( (Iterable) value ); return new ListRepresentation( getType( nested ), nested ); } else { return getSingleRepresentation( value ); } } }); return new ListRepresentation( getType( results ), results ); } public static ListRepresentation getListRepresentation( Iterable data ) { final FirstItemIterable<Representation> results = convertValuesToRepresentations( data ); return new ServerListRepresentation( getType( results ), results ); } @SuppressWarnings("unchecked") static FirstItemIterable<Representation> convertValuesToRepresentations( Iterable data ) { return new FirstItemIterable<>(new IterableWrapper<Representation,Object>(data) { @Override protected Representation underlyingObjectToObject(Object value) { return convert(value); } }); } static RepresentationType getType( FirstItemIterable<Representation> representations ) { Representation representation = representations.getFirst(); if ( representation == null ) return RepresentationType.STRING; return representation.getRepresentationType(); } static Representation getSingleRepresentation( Object result ) { if ( result == null ) { return ValueRepresentation.ofNull(); } else if ( result instanceof GraphDatabaseService ) { return new DatabaseRepresentation(); } else if ( result instanceof Node ) { return new NodeRepresentation( (Node) result ); } else if ( result instanceof Relationship ) { return new RelationshipRepresentation( (Relationship) result ); } else if ( result instanceof Double || result instanceof Float ) { return ValueRepresentation.number( ( (Number) result ).doubleValue() ); } else if ( result instanceof Long ) { return ValueRepresentation.number( ( (Long) result ).longValue() ); } else if ( result instanceof Integer ) { return ValueRepresentation.number( ( (Integer) result ).intValue() ); } else if ( result instanceof Boolean ) { return ValueRepresentation.bool( ( (Boolean) result ).booleanValue() ); } else { return ValueRepresentation.string( result.toString() ); } } }
false
community_server_src_main_java_org_neo4j_server_rest_repr_ObjectToRepresentationConverter.java
2,951
public class OutputFormatProviderTest { @Test public void shouldUseXForwardedHostHeaderWhenPresent() throws Exception { // given OutputFormatProvider provider = new OutputFormatProvider( new RepresentationFormatRepository( mock( AbstractNeoServer.class ) ) ); HttpRequestContext httpRequestContext = mock( HttpRequestContext.class ); HttpContext httpContext = mock( HttpContext.class ); when( httpContext.getRequest() ).thenReturn( httpRequestContext ); when( httpRequestContext.getBaseUri() ).thenReturn( new URI( "http://localhost:37465" ) ); when( httpRequestContext.getHeaderValue( "X-Forwarded-Host" ) ).thenReturn( "foobar.com:9999" ); Representation representation = mock( Representation.class ); OutputFormat outputFormat = provider.getValue( httpContext ); // when outputFormat.assemble( representation ); // then verify( representation ).serialize( any( RepresentationFormat.class ), eq( new URI( "http://foobar.com:9999" ) ), any( ExtensionInjector.class ) ); } @Test public void shouldUseXForwardedProtoHeaderWhenPresent() throws Exception { // given OutputFormatProvider provider = new OutputFormatProvider( new RepresentationFormatRepository( mock( AbstractNeoServer.class ) ) ); HttpRequestContext httpRequestContext = mock( HttpRequestContext.class ); HttpContext httpContext = mock( HttpContext.class ); when( httpContext.getRequest() ).thenReturn( httpRequestContext ); when( httpRequestContext.getBaseUri() ).thenReturn( new URI( "https://localhost:37465" ) ); when( httpRequestContext.getHeaderValue( "X-Forwarded-Proto" ) ).thenReturn( "http" ); Representation representation = mock( Representation.class ); OutputFormat outputFormat = provider.getValue( httpContext ); // when outputFormat.assemble( representation ); // then verify( representation ).serialize( any( RepresentationFormat.class ), eq( new URI( "http://localhost:37465" ) ), any( ExtensionInjector.class ) ); } @Test public void shouldPickFirstXForwardedHostHeaderValueFromCommaAndSpaceSeparatedList() throws Exception { // given OutputFormatProvider provider = new OutputFormatProvider( new RepresentationFormatRepository( mock( AbstractNeoServer.class ) ) ); HttpRequestContext httpRequestContext = mock( HttpRequestContext.class ); HttpContext httpContext = mock( HttpContext.class ); when( httpContext.getRequest() ).thenReturn( httpRequestContext ); when( httpRequestContext.getBaseUri() ).thenReturn( new URI( "http://localhost:37465" ) ); when( httpRequestContext.getHeaderValue( "X-Forwarded-Host" ) ).thenReturn( "foobar.com:9999, " + "bazbar.org:8888, barbar.me:7777" ); Representation representation = mock( Representation.class ); OutputFormat outputFormat = provider.getValue( httpContext ); // when outputFormat.assemble( representation ); // then verify( representation ).serialize( any( RepresentationFormat.class ), eq( new URI( "http://foobar.com:9999" ) ), any( ExtensionInjector.class ) ); } @Test public void shouldPickFirstXForwardedHostHeaderValueFromCommaSeparatedList() throws Exception { // given OutputFormatProvider provider = new OutputFormatProvider( new RepresentationFormatRepository( mock( AbstractNeoServer.class ) ) ); HttpRequestContext httpRequestContext = mock( HttpRequestContext.class ); HttpContext httpContext = mock( HttpContext.class ); when( httpContext.getRequest() ).thenReturn( httpRequestContext ); when( httpRequestContext.getBaseUri() ).thenReturn( new URI( "http://localhost:37465" ) ); when( httpRequestContext.getHeaderValue( "X-Forwarded-Host" ) ).thenReturn( "foobar.com:9999," + "bazbar.org:8888,barbar.me:7777" ); Representation representation = mock( Representation.class ); OutputFormat outputFormat = provider.getValue( httpContext ); // when outputFormat.assemble( representation ); // then verify( representation ).serialize( any( RepresentationFormat.class ), eq( new URI( "http://foobar.com:9999" ) ), any( ExtensionInjector.class ) ); } @Test public void shouldUseBaseUriOnBadXForwardedHostHeader() throws Exception { // given OutputFormatProvider provider = new OutputFormatProvider( new RepresentationFormatRepository( mock( AbstractNeoServer.class ) ) ); HttpRequestContext httpRequestContext = mock( HttpRequestContext.class ); HttpContext httpContext = mock( HttpContext.class ); when( httpContext.getRequest() ).thenReturn( httpRequestContext ); when( httpRequestContext.getBaseUri() ).thenReturn( new URI( "http://localhost:37465" ) ); when( httpRequestContext.getHeaderValue( "X-Forwarded-Host" ) ).thenReturn( ":5543:foobar.com:9999" ); Representation representation = mock( Representation.class ); OutputFormat outputFormat = provider.getValue( httpContext ); // when outputFormat.assemble( representation ); // then verify( representation ).serialize( any( RepresentationFormat.class ), eq( new URI( "http://localhost:37465" ) ), any( ExtensionInjector.class ) ); } @Test public void shouldUseBaseUriIfFirstAddressInXForwardedHostHeaderIsBad() throws Exception { // given OutputFormatProvider provider = new OutputFormatProvider( new RepresentationFormatRepository( mock( AbstractNeoServer.class ) ) ); HttpRequestContext httpRequestContext = mock( HttpRequestContext.class ); HttpContext httpContext = mock( HttpContext.class ); when( httpContext.getRequest() ).thenReturn( httpRequestContext ); when( httpRequestContext.getBaseUri() ).thenReturn( new URI( "http://localhost:37465" ) ); when( httpRequestContext.getHeaderValue( "X-Forwarded-Host" ) ).thenReturn( ":5543:foobar.com:9999, " + "bazbar.com:8888" ); Representation representation = mock( Representation.class ); OutputFormat outputFormat = provider.getValue( httpContext ); // when outputFormat.assemble( representation ); // then verify( representation ).serialize( any( RepresentationFormat.class ), eq( new URI( "http://localhost:37465" ) ), any( ExtensionInjector.class ) ); } @Test public void shouldUseBaseUriOnBadXForwardedProtoHeader() throws Exception { // given OutputFormatProvider provider = new OutputFormatProvider( new RepresentationFormatRepository( mock( AbstractNeoServer.class ) ) ); HttpRequestContext httpRequestContext = mock( HttpRequestContext.class ); HttpContext httpContext = mock( HttpContext.class ); when( httpContext.getRequest() ).thenReturn( httpRequestContext ); when( httpRequestContext.getBaseUri() ).thenReturn( new URI( "http://localhost:37465" ) ); when( httpRequestContext.getHeaderValue( "X-Forwarded-Proto" ) ).thenReturn( "%%%DEFINITELY-NOT-A-PROTO!" ); Representation representation = mock( Representation.class ); OutputFormat outputFormat = provider.getValue( httpContext ); // when outputFormat.assemble( representation ); // then verify( representation ).serialize( any( RepresentationFormat.class ), eq( new URI( "http://localhost:37465" ) ), any( ExtensionInjector.class ) ); } @Test public void shouldUseXForwardedHostAndXForwardedProtoHeadersWhenPresent() throws Exception { // given OutputFormatProvider provider = new OutputFormatProvider( new RepresentationFormatRepository( mock( AbstractNeoServer.class ) ) ); HttpRequestContext httpRequestContext = mock( HttpRequestContext.class ); HttpContext httpContext = mock( HttpContext.class ); when( httpContext.getRequest() ).thenReturn( httpRequestContext ); when( httpRequestContext.getBaseUri() ).thenReturn( new URI( "http://localhost:37465" ) ); when( httpRequestContext.getHeaderValue( "X-Forwarded-Host" ) ).thenReturn( "foobar.com:9999" ); when( httpRequestContext.getHeaderValue( "X-Forwarded-Proto" ) ).thenReturn( "https" ); Representation representation = mock( Representation.class ); OutputFormat outputFormat = provider.getValue( httpContext ); // when outputFormat.assemble( representation ); // then verify( representation ).serialize( any( RepresentationFormat.class ), eq( new URI( "https://foobar.com:9999" ) ), any( ExtensionInjector.class ) ); } @Test public void shouldUseDefaultPortIfNoPortNumberSpecifiedOnXForwardedHostHeader() throws Exception { // given OutputFormatProvider provider = new OutputFormatProvider( new RepresentationFormatRepository( mock( AbstractNeoServer.class ) ) ); HttpRequestContext httpRequestContext = mock( HttpRequestContext.class ); HttpContext httpContext = mock( HttpContext.class ); when( httpContext.getRequest() ).thenReturn( httpRequestContext ); when( httpRequestContext.getBaseUri() ).thenReturn( new URI( "http://localhost" ) ); when( httpRequestContext.getHeaderValue( "X-Forwarded-Host" ) ).thenReturn( "foobar.com" ); Representation representation = mock( Representation.class ); OutputFormat outputFormat = provider.getValue( httpContext ); // when outputFormat.assemble( representation ); // then verify( representation ).serialize( any( RepresentationFormat.class ), eq( new URI( "http://foobar.com" ) ), any( ExtensionInjector.class ) ); } }
false
community_server_src_test_java_org_neo4j_server_rest_repr_OutputFormatProviderTest.java
2,952
private class ForwardedProto { private final String headerValue; public ForwardedProto( String headerValue ) { if ( headerValue != null ) { this.headerValue = headerValue; } else { this.headerValue = ""; } } public boolean isValid() { return headerValue.toLowerCase().equals( "http" ) || headerValue.toLowerCase().equals( "https" ); } public String getScheme() { return headerValue; } }
false
community_server_src_main_java_org_neo4j_server_rest_repr_OutputFormatProvider.java
2,953
private class ForwardedHost { private String host; private int port = -1; private boolean isValid = false; public ForwardedHost( String headerValue ) { if ( headerValue == null ) { this.isValid = false; return; } String firstHostInXForwardedHostHeader = headerValue.split( "," )[0].trim(); try { UriBuilder.fromUri( firstHostInXForwardedHostHeader ).build(); } catch ( IllegalArgumentException ex ) { this.isValid = false; return; } String[] strings = firstHostInXForwardedHostHeader.split( ":" ); if ( strings.length > 0 ) { this.host = strings[0]; isValid = true; } if ( strings.length > 1 ) { this.port = Integer.valueOf( strings[1] ); isValid = true; } if ( strings.length > 2 ) { this.isValid = false; } } public boolean hasExplicitlySpecifiedPort() { return port >= 0; } public String getHost() { return host; } public int getPort() { return port; } }
false
community_server_src_main_java_org_neo4j_server_rest_repr_OutputFormatProvider.java
2,954
@Provider public final class OutputFormatProvider extends InjectableProvider<OutputFormat> { private final RepresentationFormatRepository repository; public OutputFormatProvider( RepresentationFormatRepository repository ) { super( OutputFormat.class ); this.repository = repository; } @Override public OutputFormat getValue( HttpContext context ) { try { return repository.outputFormat( context.getRequest() .getAcceptableMediaTypes(), getBaseUri( context ), context.getRequest().getRequestHeaders() ); } catch ( MediaTypeNotSupportedException e ) { throw new WebApplicationException( Response.status( Status.NOT_ACCEPTABLE ) .entity( e.getMessage() ) .build() ); } catch ( URISyntaxException e ) { throw new WebApplicationException( Response.status( Status.INTERNAL_SERVER_ERROR ) .entity( e.getMessage() ) .build() ); } } private URI getBaseUri( HttpContext context ) throws URISyntaxException { UriBuilder builder = UriBuilder.fromUri( context.getRequest().getBaseUri() ); ForwardedHost forwardedHost = new ForwardedHost( context.getRequest().getHeaderValue( "X-Forwarded-Host" ) ); ForwardedProto xForwardedProto = new ForwardedProto( context.getRequest().getHeaderValue( "X-Forwarded-Proto" ) ); if ( forwardedHost.isValid ) { builder.host( forwardedHost.getHost() ); if ( forwardedHost.hasExplicitlySpecifiedPort() ) { builder.port( forwardedHost.getPort() ); } } if ( xForwardedProto.isValid() ) { builder.scheme( xForwardedProto.getScheme() ); } return builder.build(); } private class ForwardedHost { private String host; private int port = -1; private boolean isValid = false; public ForwardedHost( String headerValue ) { if ( headerValue == null ) { this.isValid = false; return; } String firstHostInXForwardedHostHeader = headerValue.split( "," )[0].trim(); try { UriBuilder.fromUri( firstHostInXForwardedHostHeader ).build(); } catch ( IllegalArgumentException ex ) { this.isValid = false; return; } String[] strings = firstHostInXForwardedHostHeader.split( ":" ); if ( strings.length > 0 ) { this.host = strings[0]; isValid = true; } if ( strings.length > 1 ) { this.port = Integer.valueOf( strings[1] ); isValid = true; } if ( strings.length > 2 ) { this.isValid = false; } } public boolean hasExplicitlySpecifiedPort() { return port >= 0; } public String getHost() { return host; } public int getPort() { return port; } } private class ForwardedProto { private final String headerValue; public ForwardedProto( String headerValue ) { if ( headerValue != null ) { this.headerValue = headerValue; } else { this.headerValue = ""; } } public boolean isValid() { return headerValue.toLowerCase().equals( "http" ) || headerValue.toLowerCase().equals( "https" ); } public String getScheme() { return headerValue; } } }
false
community_server_src_main_java_org_neo4j_server_rest_repr_OutputFormatProvider.java
2,955
{ public void write( OutputStream output ) throws IOException, WebApplicationException { RepresentationFormat outputStreamFormat = streamingFormat.writeTo( output ); try { representation.serialize( outputStreamFormat, baseUri, extensions ); if ( !mustFail ) representationWriteHandler.onRepresentationWritten(); } catch ( Exception e ) { if ( e instanceof NodeNotFoundException || e instanceof RelationshipNotFoundException ) { throw new WebApplicationException( notFound( e ) ); } if ( e instanceof BadInputException ) { throw new WebApplicationException( badRequest( e ) ); } throw new WebApplicationException( e, serverError( e ) ); } finally { representationWriteHandler.onRepresentationFinal(); } } };
false
community_server_src_main_java_org_neo4j_server_rest_repr_OutputFormat.java
2,956
public class OutputFormat { private static final String UTF8 = "UTF-8"; private final RepresentationFormat format; private final ExtensionInjector extensions; private final URI baseUri; private RepresentationWriteHandler representationWriteHandler = RepresentationWriteHandler.DO_NOTHING; public OutputFormat( RepresentationFormat format, URI baseUri, ExtensionInjector extensions ) { this.format = format; this.baseUri = baseUri; this.extensions = extensions; } public void setRepresentationWriteHandler( RepresentationWriteHandler representationWriteHandler ) { this.representationWriteHandler = representationWriteHandler; } public final Response ok( Representation representation ) { if ( representation.isEmpty() ) { return noContent(); } return response( Response.ok(), representation ); } public final <REPR extends Representation & EntityRepresentation> Response okIncludeLocation( REPR representation ) throws BadInputException { if ( representation.isEmpty() ) { return noContent(); } return response( Response.ok().header( HttpHeaders.LOCATION, uri( representation ) ), representation ); } public final <REPR extends Representation & EntityRepresentation> Response created( REPR representation ) throws BadInputException { return response( Response.created( uri( representation ) ), representation ); } public final Response response( Status status, Representation representation ) throws BadInputException { return response( Response.status( status ), representation ); } public Response badRequest( Throwable exception ) { return response( Response.status( BAD_REQUEST ), new ExceptionRepresentation( exception ) ); } public Response notFound( Throwable exception ) { return response( Response.status( Status.NOT_FOUND ), new ExceptionRepresentation( exception ) ); } public Response notFound() { representationWriteHandler.onRepresentationFinal(); return Response.status( Status.NOT_FOUND ) .build(); } public Response conflict( Throwable exception ) { return response( Response.status( Status.CONFLICT ), new ExceptionRepresentation( exception ) ); } public final <REPR extends Representation & EntityRepresentation> Response conflict( REPR representation ) throws BadInputException { return response( Response.status( Status.CONFLICT ), representation ); } public Response serverError( Throwable exception ) { return response( Response.status( Status.INTERNAL_SERVER_ERROR ), new ExceptionRepresentation( exception ) ); } private URI uri( EntityRepresentation representation ) throws BadInputException { return URI.create( assemble( representation.selfUri() ) ); } protected Response response( ResponseBuilder response, Representation representation ) { return formatRepresentation( response, representation ) .type( HttpHeaderUtils.mediaTypeWithCharsetUtf8( getMediaType() ) ) .build(); } private ResponseBuilder formatRepresentation( ResponseBuilder response, final Representation representation ) { representationWriteHandler.onRepresentationStartWriting(); boolean mustFail = representation instanceof ExceptionRepresentation; if ( format instanceof StreamingFormat ) { return response.entity( stream( representation, (StreamingFormat) format, mustFail ) ); } else { return response.entity( toBytes( assemble( representation ), mustFail ) ); } } private Object stream( final Representation representation, final StreamingFormat streamingFormat, final boolean mustFail ) { return new StreamingOutput() { public void write( OutputStream output ) throws IOException, WebApplicationException { RepresentationFormat outputStreamFormat = streamingFormat.writeTo( output ); try { representation.serialize( outputStreamFormat, baseUri, extensions ); if ( !mustFail ) representationWriteHandler.onRepresentationWritten(); } catch ( Exception e ) { if ( e instanceof NodeNotFoundException || e instanceof RelationshipNotFoundException ) { throw new WebApplicationException( notFound( e ) ); } if ( e instanceof BadInputException ) { throw new WebApplicationException( badRequest( e ) ); } throw new WebApplicationException( e, serverError( e ) ); } finally { representationWriteHandler.onRepresentationFinal(); } } }; } public static void write( Representation representation, RepresentationFormat format, URI baseUri ) { representation.serialize( format, baseUri, null ); } private byte[] toBytes( String entity, boolean mustFail ) { byte[] entityAsBytes; try { entityAsBytes = entity.getBytes( UTF8 ); if (! mustFail) representationWriteHandler.onRepresentationWritten(); } catch ( UnsupportedEncodingException e ) { throw new RuntimeException( "Could not encode string as UTF-8", e ); } finally { representationWriteHandler.onRepresentationFinal(); } return entityAsBytes; } public MediaType getMediaType() { return format.mediaType; } public String assemble( Representation representation ) { return representation.serialize( format, baseUri, extensions ); } public Response noContent() { representationWriteHandler.onRepresentationStartWriting(); representationWriteHandler.onRepresentationWritten(); representationWriteHandler.onRepresentationFinal(); return Response.status( Status.NO_CONTENT ) .build(); } public Response methodNotAllowed( UnsupportedOperationException e ) { return response( Response.status( 405 ), new ExceptionRepresentation( e ) ); } public Response ok() { representationWriteHandler.onRepresentationStartWriting(); representationWriteHandler.onRepresentationWritten(); representationWriteHandler.onRepresentationFinal(); return Response.ok().build(); } public Response badRequest( MediaType mediaType, String entity ) { representationWriteHandler.onRepresentationStartWriting(); representationWriteHandler.onRepresentationFinal(); return Response.status( BAD_REQUEST ).type( mediaType ).entity( entity ).build(); } }
false
community_server_src_main_java_org_neo4j_server_rest_repr_OutputFormat.java
2,957
return new FirstItemIterable<>(new IterableWrapper<Representation,Object>(data) { @Override protected Representation underlyingObjectToObject(Object value) { return convert(value); } });
false
community_server_src_main_java_org_neo4j_server_rest_repr_ObjectToRepresentationConverter.java
2,958
final FirstItemIterable<Representation> results = new FirstItemIterable<>(new IteratorWrapper<Representation, Object>(data) { @Override protected Representation underlyingObjectToObject(Object value) { if ( value instanceof Iterable ) { FirstItemIterable<Representation> nested = convertValuesToRepresentations( (Iterable) value ); return new ListRepresentation( getType( nested ), nested ); } else { return getSingleRepresentation( value ); } } });
false
community_server_src_main_java_org_neo4j_server_rest_repr_ObjectToRepresentationConverter.java
2,959
private static abstract class PropertyGetter { PropertyGetter( Method method ) { if ( method.getParameterTypes().length != 0 ) { throw new IllegalStateException( "Property getter method may not have any parameters." ); } if ( !Representation.class.isAssignableFrom( (Class<?>) method.getReturnType() ) ) { throw new IllegalStateException( "Property getter must return Representation object." ); } } void putTo( MappingSerializer serializer, ObjectRepresentation object, String key ) { Object value = get( object ); if ( value != null ) ( (Representation) value ).putTo( serializer, key ); } abstract Object get( ObjectRepresentation object ); }
false
community_server_src_main_java_org_neo4j_server_rest_repr_ObjectRepresentation.java
2,960
public class MediaTypeNotSupportedException extends WebApplicationException { private static final long serialVersionUID = 5159216782240337940L; public MediaTypeNotSupportedException( Response.Status status, Collection<MediaType> supported, MediaType... requested ) { super( createResponse( status, message( supported, requested ) ) ); } private static Response createResponse( Response.Status status, String message ) { return Response.status( status ) .entity( message ) .build(); } private static String message( Collection<MediaType> supported, MediaType[] requested ) { StringBuilder message = new StringBuilder( "No matching representation format found.\n" ); if ( requested.length == 0 ) { message.append( "No requested representation format supplied." ); } else if ( requested.length == 1 ) { message.append( "Request format: " ) .append( requested[0] ) .append( "\n" ); } else { message.append( "Requested formats:\n" ); for ( int i = 0; i < requested.length; i++ ) { message.append( " " ) .append( i ) .append( ". " ); message.append( requested[i] ) .append( "\n" ); } } message.append( "Supported representation formats:" ); if ( supported.isEmpty() ) { message.append( " none" ); } else { for ( MediaType type : supported ) { message.append( "\n * " ) .append( type ); } } return message.toString(); } }
false
community_server_src_main_java_org_neo4j_server_rest_repr_MediaTypeNotSupportedException.java
2,961
{ @Override Object get( ObjectRepresentation object ) { Throwable e; try { return method.invoke( object ); } catch ( InvocationTargetException ex ) { e = ex.getTargetException(); if ( e instanceof RuntimeException ) { throw (RuntimeException) e; } else if ( e instanceof Error ) { throw (Error) e; } } catch ( Exception ex ) { e = ex; } throw new IllegalStateException( "Serialization failure", e ); } };
false
community_server_src_main_java_org_neo4j_server_rest_repr_ObjectRepresentation.java
2,962
public abstract class ObjectRepresentation extends MappingRepresentation { @Target( ElementType.METHOD ) @Retention( RetentionPolicy.RUNTIME ) protected @interface Mapping { String value(); } private final static ConcurrentHashMap<Class<?>, Map<String, PropertyGetter>> serializations = new ConcurrentHashMap<Class<?>, Map<String, PropertyGetter>>(); private final Map<String, PropertyGetter> serialization = serialization( getClass() ); ObjectRepresentation( RepresentationType type ) { super( type ); } public ObjectRepresentation( String type ) { super( type ); } private static Map<String, PropertyGetter> serialization( Class<? extends ObjectRepresentation> type ) { Map<String, PropertyGetter> serialization = serializations.get( type ); if ( serialization == null ) { synchronized ( type ) { serialization = serializations.get( type ); if ( serialization == null ) { serialization = new HashMap<String, PropertyGetter>(); for ( Method method : type.getMethods() ) { Mapping property = method.getAnnotation( Mapping.class ); if ( property != null ) { serialization.put( property.value(), getter( method ) ); } } serializations.put(type, serialization); } } } return serialization; } private static PropertyGetter getter( final Method method ) { // If this turns out to be a bottle neck we could use a byte code // generation library, such as ASM, instead of reflection. return new PropertyGetter( method ) { @Override Object get( ObjectRepresentation object ) { Throwable e; try { return method.invoke( object ); } catch ( InvocationTargetException ex ) { e = ex.getTargetException(); if ( e instanceof RuntimeException ) { throw (RuntimeException) e; } else if ( e instanceof Error ) { throw (Error) e; } } catch ( Exception ex ) { e = ex; } throw new IllegalStateException( "Serialization failure", e ); } }; } private static abstract class PropertyGetter { PropertyGetter( Method method ) { if ( method.getParameterTypes().length != 0 ) { throw new IllegalStateException( "Property getter method may not have any parameters." ); } if ( !Representation.class.isAssignableFrom( (Class<?>) method.getReturnType() ) ) { throw new IllegalStateException( "Property getter must return Representation object." ); } } void putTo( MappingSerializer serializer, ObjectRepresentation object, String key ) { Object value = get( object ); if ( value != null ) ( (Representation) value ).putTo( serializer, key ); } abstract Object get( ObjectRepresentation object ); } @Override protected final void serialize( MappingSerializer serializer ) { for ( Map.Entry<String, PropertyGetter> property : serialization.entrySet() ) { property.getValue() .putTo( serializer, this, property.getKey() ); } extraData( serializer ); } void extraData( MappingSerializer serializer ) { } }
false
community_server_src_main_java_org_neo4j_server_rest_repr_ObjectRepresentation.java
2,963
public class NodeRepresentationTest { @Test public void shouldHaveSelfLink() throws BadInputException { assertUriMatches( uriPattern( "" ), noderep( 1234 ).selfUri() ); } @Test public void shouldHaveAllRelationshipsLink() throws BadInputException { assertUriMatches( uriPattern( "/relationships/all" ), noderep( 1234 ).allRelationshipsUri() ); } @Test public void shouldHaveIncomingRelationshipsLink() throws BadInputException { assertUriMatches( uriPattern( "/relationships/in" ), noderep( 1234 ).incomingRelationshipsUri() ); } @Test public void shouldHaveOutgoingRelationshipsLink() throws BadInputException { assertUriMatches( uriPattern( "/relationships/out" ), noderep( 1234 ).outgoingRelationshipsUri() ); } @Test public void shouldHaveAllTypedRelationshipsLinkTemplate() throws BadInputException { assertUriMatches( uriPattern( "/relationships/all/\\{-list\\|&\\|types\\}" ), noderep( 1234 ).allTypedRelationshipsUriTemplate() ); } @Test public void shouldHaveIncomingTypedRelationshipsLinkTemplate() throws BadInputException { assertUriMatches( uriPattern( "/relationships/in/\\{-list\\|&\\|types\\}" ), noderep( 1234 ).incomingTypedRelationshipsUriTemplate() ); } @Test public void shouldHaveOutgoingTypedRelationshipsLinkTemplate() throws BadInputException { assertUriMatches( uriPattern( "/relationships/out/\\{-list\\|&\\|types\\}" ), noderep( 1234 ).outgoingTypedRelationshipsUriTemplate() ); } @Test public void shouldHaveRelationshipCreationLink() throws BadInputException { assertUriMatches( uriPattern( "/relationships" ), noderep( 1234 ).relationshipCreationUri() ); } @Test public void shouldHavePropertiesLink() throws BadInputException { assertUriMatches( uriPattern( "/properties" ), noderep( 1234 ).propertiesUri() ); } @Test public void shouldHavePropertyLinkTemplate() throws BadInputException { assertUriMatches( uriPattern( "/properties/\\{key\\}" ), noderep( 1234 ).propertyUriTemplate() ); } @Test public void shouldHaveTraverseLinkTemplate() throws BadInputException { assertUriMatches( uriPattern( "/traverse/\\{returnType\\}" ), noderep( 1234 ).traverseUriTemplate() ); } @Test public void shouldSerialiseToMap() { Map<String, Object> repr = serialize( noderep( 1234 ) ); assertNotNull( repr ); verifySerialisation( repr ); } @Test public void shouldHaveLabelsLink() throws BadInputException { assertUriMatches( uriPattern( "/labels" ), noderep( 1234 ).labelsUriTemplate() ); } private NodeRepresentation noderep( long id ) { return new NodeRepresentation( node( id, properties() ) ); } public static void verifySerialisation( Map<String, Object> noderep ) { assertUriMatches( uriPattern( "" ), noderep.get( "self" ) .toString() ); assertUriMatches( uriPattern( "/relationships" ), noderep.get( "create_relationship" ) .toString() ); assertUriMatches( uriPattern( "/relationships/all" ), noderep.get( "all_relationships" ) .toString() ); assertUriMatches( uriPattern( "/relationships/in" ), noderep.get( "incoming_relationships" ) .toString() ); assertUriMatches( uriPattern( "/relationships/out" ), noderep.get( "outgoing_relationships" ) .toString() ); assertUriMatches( uriPattern( "/relationships/all/\\{-list\\|&\\|types\\}" ), (String) noderep.get( "all_typed_relationships" ) ); assertUriMatches( uriPattern( "/relationships/in/\\{-list\\|&\\|types\\}" ), (String) noderep.get( "incoming_typed_relationships" ) ); assertUriMatches( uriPattern( "/relationships/out/\\{-list\\|&\\|types\\}" ), (String) noderep.get( "outgoing_typed_relationships" ) ); assertUriMatches( uriPattern( "/properties" ), noderep.get( "properties" ) .toString() ); assertUriMatches( uriPattern( "/properties/\\{key\\}" ), (String) noderep.get( "property" ) ); assertUriMatches( uriPattern( "/traverse/\\{returnType\\}" ), (String) noderep.get( "traverse" ) ); assertUriMatches( uriPattern( "/labels" ), (String) noderep.get( "labels" ) ); assertNotNull( noderep.get( "data" ) ); } }
false
community_server_src_test_java_org_neo4j_server_rest_repr_NodeRepresentationTest.java
2,964
{ @Override protected Representation underlyingObjectToObject( Node node ) { return new NodeRepresentation( node ); } } );
false
community_server_src_main_java_org_neo4j_server_rest_repr_NodeRepresentation.java
2,965
public final class NodeRepresentation extends ObjectRepresentation implements ExtensibleRepresentation, EntityRepresentation { private final Node node; public NodeRepresentation( Node node ) { super( RepresentationType.NODE ); this.node = node; } @Override public String getIdentity() { return Long.toString( node.getId() ); } @Override @Mapping( "self" ) public ValueRepresentation selfUri() { return ValueRepresentation.uri( path( "" ) ); } public long getId() { return node.getId(); } private String path( String path ) { return "node/" + node.getId() + path; } static String path( Node node ) { return "node/" + node.getId(); } @Mapping( "create_relationship" ) public ValueRepresentation relationshipCreationUri() { return ValueRepresentation.uri( path( "/relationships" ) ); } @Mapping( "all_relationships" ) public ValueRepresentation allRelationshipsUri() { return ValueRepresentation.uri( path( "/relationships/all" ) ); } @Mapping( "incoming_relationships" ) public ValueRepresentation incomingRelationshipsUri() { return ValueRepresentation.uri( path( "/relationships/in" ) ); } @Mapping( "outgoing_relationships" ) public ValueRepresentation outgoingRelationshipsUri() { return ValueRepresentation.uri( path( "/relationships/out" ) ); } @Mapping( "all_typed_relationships" ) public ValueRepresentation allTypedRelationshipsUriTemplate() { return ValueRepresentation.template( path( "/relationships/all/{-list|&|types}" ) ); } @Mapping( "incoming_typed_relationships" ) public ValueRepresentation incomingTypedRelationshipsUriTemplate() { return ValueRepresentation.template( path( "/relationships/in/{-list|&|types}" ) ); } @Mapping( "outgoing_typed_relationships" ) public ValueRepresentation outgoingTypedRelationshipsUriTemplate() { return ValueRepresentation.template( path( "/relationships/out/{-list|&|types}" ) ); } @Mapping( "labels" ) public ValueRepresentation labelsUriTemplate() { return ValueRepresentation.template( path( "/labels" ) ); } @Mapping( "properties" ) public ValueRepresentation propertiesUri() { return ValueRepresentation.uri( path( "/properties" ) ); } @Mapping( "property" ) public ValueRepresentation propertyUriTemplate() { return ValueRepresentation.template( path( "/properties/{key}" ) ); } @Mapping( "traverse" ) public ValueRepresentation traverseUriTemplate() { return ValueRepresentation.template( path( "/traverse/{returnType}" ) ); } @Mapping( "paged_traverse" ) public ValueRepresentation pagedTraverseUriTemplate() { return ValueRepresentation.template( path( "/paged/traverse/{returnType}{?pageSize,leaseTime}" ) ); } @Override void extraData( MappingSerializer serializer ) { MappingWriter writer = serializer.writer; MappingWriter properties = writer.newMapping( RepresentationType.PROPERTIES, "data" ); new PropertiesRepresentation( node ).serialize( properties ); if ( writer.isInteractive() ) { serializer.putList( "relationship_types", ListRepresentation.relationshipTypes( GlobalGraphOperations.at( node.getGraphDatabase() ).getAllRelationshipTypes() ) ); } properties.done(); } public static ListRepresentation list( Iterable<Node> nodes ) { return new ListRepresentation( RepresentationType.NODE, new IterableWrapper<Representation, Node>( nodes ) { @Override protected Representation underlyingObjectToObject( Node node ) { return new NodeRepresentation( node ); } } ); } }
false
community_server_src_main_java_org_neo4j_server_rest_repr_NodeRepresentation.java
2,966
public class NodeIndexRootRepresentation extends MappingRepresentation { private IndexManager indexManager; public NodeIndexRootRepresentation( IndexManager indexManager ) { super( "node-index" ); this.indexManager = indexManager; } @Override protected void serialize( final MappingSerializer serializer ) { indexManager.nodeIndexNames(); for ( String indexName : indexManager.nodeIndexNames() ) { Index<Node> index = indexManager.forNodes( indexName ); serializer.putMapping( indexName, new NodeIndexRepresentation( indexName, indexManager.getConfiguration( index ) ) ); } } }
false
community_server_src_main_java_org_neo4j_server_rest_repr_NodeIndexRootRepresentation.java
2,967
public class NodeIndexRepresentation extends IndexRepresentation { public NodeIndexRepresentation( String name ) { this( name, Collections.EMPTY_MAP ); } public NodeIndexRepresentation( String name, Map<String, String> type ) { super( name, type ); } public String propertyContainerType() { return "node"; } }
false
community_server_src_main_java_org_neo4j_server_rest_repr_NodeIndexRepresentation.java
2,968
public class NodeAutoIndexRepresentation extends IndexRepresentation { public NodeAutoIndexRepresentation() { super("", Collections.EMPTY_MAP); } @Override protected String path() { return RestfulGraphDatabase.PATH_AUTO_INDEX.replace("{type}", RestfulGraphDatabase.NODE_AUTO_INDEX_TYPE) + "/"; } @Override protected String propertyContainerType() { return null; } }
false
community_server_src_main_java_org_neo4j_server_rest_repr_NodeAutoIndexRepresentation.java
2,969
public class IndexMapReference { private volatile IndexMap indexMap = new IndexMap(); public IndexMap getIndexMapCopy() { return indexMap.clone(); } public IndexProxy getIndexProxy( long indexId ) { return indexMap.getIndexProxy( indexId ); } public Iterable<IndexProxy> getAllIndexProxies() { return indexMap.getAllIndexProxies(); } public void setIndexMap( IndexMap newIndexMap ) { // ASSUMPTION: Only called at shutdown or during commit (single-threaded in each case) indexMap = newIndexMap; } public IndexProxy removeIndexProxy( long indexId ) { // ASSUMPTION: Only called at shutdown or during commit (single-threaded in each case) IndexMap newIndexMap = getIndexMapCopy(); IndexProxy indexProxy = newIndexMap.removeIndexProxy( indexId ); setIndexMap( newIndexMap ); return indexProxy; } public Iterable<IndexProxy> clear() { // ASSUMPTION: Only called at shutdown when there are no other calls to setIndexMap IndexMap oldIndexMap = indexMap; setIndexMap( new IndexMap() ); return oldIndexMap.getAllIndexProxies(); } public IndexUpdaterMap getIndexUpdaterMap( IndexUpdateMode mode ) { return new IndexUpdaterMap( mode, indexMap ); } }
false
community_kernel_src_main_java_org_neo4j_kernel_impl_api_index_IndexMapReference.java
2,970
{ @Override public void run() throws IOException { outer.force(); } } );
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_ContractCheckingIndexProxyTest.java
2,971
public class IndexIT extends KernelIntegrationTest { int labelId = 5, propertyKey = 8; @Test public void addIndexRuleInATransaction() throws Exception { // GIVEN IndexDescriptor expectedRule; { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); // WHEN expectedRule = statement.indexCreate( labelId, propertyKey ); commit(); } // THEN { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); assertEquals( asSet( expectedRule ), asSet( statement.indexesGetForLabel( labelId ) ) ); assertEquals( expectedRule, statement.indexesGetForLabelAndPropertyKey( labelId, propertyKey ) ); commit(); } } @Test public void committedAndTransactionalIndexRulesShouldBeMerged() throws Exception { // GIVEN IndexDescriptor existingRule; { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); existingRule = statement.indexCreate( labelId, propertyKey ); commit(); } // WHEN IndexDescriptor addedRule; Set<IndexDescriptor> indexRulesInTx; { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); int propertyKey2 = 10; addedRule = statement.indexCreate( labelId, propertyKey2 ); indexRulesInTx = asSet( statement.indexesGetForLabel( labelId ) ); commit(); } // THEN assertEquals( asSet( existingRule, addedRule ), indexRulesInTx ); } @Test public void rollBackIndexRuleShouldNotBeCommitted() throws Exception { // GIVEN { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); // WHEN statement.indexCreate( labelId, propertyKey ); // don't mark as success rollback(); } // THEN { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); assertEquals( emptySetOf( IndexDescriptor.class ), asSet( statement.indexesGetForLabel( labelId ) ) ); commit(); } } @Test public void shouldRemoveAConstraintIndexWithoutOwnerInRecovery() throws Exception { // given Transactor transactor = new Transactor( db.getDependencyResolver().resolveDependency( TransactionManager.class ), db.getDependencyResolver().resolveDependency( PersistenceManager.class ) ); transactor.execute( ConstraintIndexCreator.createConstraintIndex( labelId, propertyKey ) ); // when restartDb(); // then { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); assertEquals( emptySetOf( IndexDescriptor.class ), asSet( statement.indexesGetForLabel( labelId ) ) ); commit(); } } @Test public void shouldDisallowDroppingIndexThatDoesNotExist() throws Exception { // given IndexDescriptor index; { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); index = statement.indexCreate( labelId, propertyKey ); commit(); } { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); statement.indexDrop( index ); commit(); } // when try { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); statement.indexDrop( index ); commit(); } // then catch ( SchemaKernelException e ) { assertEquals( "Unable to drop index on :label[5](property[8]): No such INDEX ON :label[5](property[8]).", e.getMessage() ); } } @Test public void shouldFailToCreateIndexWhereAConstraintAlreadyExists() throws Exception { // given { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); statement.uniquenessConstraintCreate( labelId, propertyKey ); commit(); } // when try { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); statement.indexCreate( labelId, propertyKey ); commit(); fail( "expected exception" ); } // then catch ( SchemaKernelException e ) { assertEquals( "Already constrained CONSTRAINT ON ( n:label[5] ) " + "ASSERT n.property[8] IS UNIQUE.", e.getMessage() ); } } @Test public void shouldListConstraintIndexesInTheBeansAPI() throws Exception { // given { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); statement.uniquenessConstraintCreate( statement.labelGetOrCreateForName( "Label1" ), statement.propertyKeyGetOrCreateForName( "property1" ) ); commit(); } // when { schemaWriteOperationsInNewTransaction(); Set<IndexDefinition> indexes = asSet( db.schema().getIndexes() ); // then assertEquals( 1, indexes.size() ); IndexDefinition index = indexes.iterator().next(); assertEquals( "Label1", index.getLabel().name() ); assertEquals( asSet( "property1" ), asSet( index.getPropertyKeys() ) ); assertTrue( "index should be a constraint index", index.isConstraintIndex() ); // when try { index.drop(); fail( "expected exception" ); } // then catch ( IllegalStateException e ) { assertEquals( "Constraint indexes cannot be dropped directly, " + "instead drop the owning uniqueness constraint.", e.getMessage() ); } commit(); } } @Test public void shouldNotListConstraintIndexesAmongIndexes() throws Exception { // given { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); statement.uniquenessConstraintCreate( labelId, propertyKey ); commit(); } // then/when { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); assertFalse( statement.indexesGetAll().hasNext() ); assertFalse( statement.indexesGetForLabel( labelId ).hasNext() ); } } @Test public void shouldNotListIndexesAmongConstraintIndexes() throws Exception { // given { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); statement.indexCreate( labelId, propertyKey ); commit(); } // then/when { SchemaWriteOperations statement = schemaWriteOperationsInNewTransaction(); assertFalse( statement.uniqueIndexesGetAll().hasNext() ); assertFalse( statement.uniqueIndexesGetForLabel( labelId ).hasNext() ); } } }
false
community_kernel_src_test_java_org_neo4j_kernel_impl_api_index_IndexIT.java
2,972
static class PathPrinter implements Traversal.PathDescriptor<Path> { private final String nodePropertyKey; public PathPrinter( String nodePropertyKey ) { this.nodePropertyKey = nodePropertyKey; } @Override public String nodeRepresentation( Path path, Node node ) { return "(" + node.getProperty( nodePropertyKey, "" ) + ")"; } @Override public String relationshipRepresentation( Path path, Node from, Relationship relationship ) { String prefix = "--", suffix = "--"; if ( from.equals( relationship.getEndNode() ) ) { prefix = "<--"; } else { suffix = "-->"; } return prefix + "[" + relationship.getType().name() + "]" + suffix; } }
false
community_embedded-examples_src_main_java_org_neo4j_examples_orderedpath_OrderedPath.java
2,973
public class OrderedPath { private static final RelationshipType REL1 = withName( "REL1" ), REL2 = withName( "REL2" ), REL3 = withName( "REL3" ); static final String DB_PATH = "target/neo4j-orderedpath-db"; GraphDatabaseService db; public OrderedPath( GraphDatabaseService db ) { this.db = db; } public static void main( String[] args ) { GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase( DB_PATH ); OrderedPath op = new OrderedPath( db ); op.shutdownGraph(); } public Node createTheGraph() { try ( Transaction tx = db.beginTx() ) { // START SNIPPET: createGraph Node A = db.createNode(); Node B = db.createNode(); Node C = db.createNode(); Node D = db.createNode(); A.createRelationshipTo( C, REL2 ); C.createRelationshipTo( D, REL3 ); A.createRelationshipTo( B, REL1 ); B.createRelationshipTo( C, REL2 ); // END SNIPPET: createGraph A.setProperty( "name", "A" ); B.setProperty( "name", "B" ); C.setProperty( "name", "C" ); D.setProperty( "name", "D" ); tx.success(); return A; } } public void shutdownGraph() { try { if ( db != null ) { db.shutdown(); } } finally { db = null; } } public TraversalDescription findPaths() { // START SNIPPET: walkOrderedPath final ArrayList<RelationshipType> orderedPathContext = new ArrayList<RelationshipType>(); orderedPathContext.add( REL1 ); orderedPathContext.add( withName( "REL2" ) ); orderedPathContext.add( withName( "REL3" ) ); TraversalDescription td = Traversal.description() .evaluator( new Evaluator() { @Override public Evaluation evaluate( final Path path ) { if ( path.length() == 0 ) { return Evaluation.EXCLUDE_AND_CONTINUE; } RelationshipType expectedType = orderedPathContext.get( path.length() - 1 ); boolean isExpectedType = path.lastRelationship() .isType( expectedType ); boolean included = path.length() == orderedPathContext.size() && isExpectedType; boolean continued = path.length() < orderedPathContext.size() && isExpectedType; return Evaluation.of( included, continued ); } } ) .uniqueness( Uniqueness.NODE_PATH ); // END SNIPPET: walkOrderedPath return td; } String printPaths( TraversalDescription td, Node A ) { try ( Transaction transaction = db.beginTx() ) { String output = ""; // START SNIPPET: printPath Traverser traverser = td.traverse( A ); PathPrinter pathPrinter = new PathPrinter( "name" ); for ( Path path : traverser ) { output += Traversal.pathToString( path, pathPrinter ); } // END SNIPPET: printPath output += "\n"; return output; } } // START SNIPPET: pathPrinter static class PathPrinter implements Traversal.PathDescriptor<Path> { private final String nodePropertyKey; public PathPrinter( String nodePropertyKey ) { this.nodePropertyKey = nodePropertyKey; } @Override public String nodeRepresentation( Path path, Node node ) { return "(" + node.getProperty( nodePropertyKey, "" ) + ")"; } @Override public String relationshipRepresentation( Path path, Node from, Relationship relationship ) { String prefix = "--", suffix = "--"; if ( from.equals( relationship.getEndNode() ) ) { prefix = "<--"; } else { suffix = "-->"; } return prefix + "[" + relationship.getType().name() + "]" + suffix; } } // END SNIPPET: pathPrinter }
false
community_embedded-examples_src_main_java_org_neo4j_examples_orderedpath_OrderedPath.java
2,974
{ @Override public Evaluation evaluate( Path path ) { boolean endNodeIsTarget = path.endNode().equals( target ); return Evaluation.of( endNodeIsTarget, !endNodeIsTarget ); } } );
false
community_embedded-examples_src_test_java_org_neo4j_examples_UniquenessOfPathsDocTest.java
2,975
public class UniquenessOfPathsDocTest extends ImpermanentGraphJavaDocTestBase { /** * Uniqueness of Paths in traversals. * * This example is demonstrating the use of node uniqueness. * Below an imaginary domain graph with Principals * that own pets that are descendant to other pets. * * @@graph * * In order to return all descendants * of +Pet0+ which have the relation +owns+ to +Principal1+ (+Pet1+ and +Pet3+), * the Uniqueness of the traversal needs to be set to * +NODE_PATH+ rather than the default +NODE_GLOBAL+ so that nodes * can be traversed more that once, and paths that have * different nodes but can have some nodes in common (like the * start and end node) can be returned. * * @@traverser * * This will return the following paths: * * @@output * * In the default `path.toString()` implementation, `(1)--[knows,2]-->(4)` denotes * a node with ID=1 having a relationship with ID 2 or type `knows` to a node with ID-4. * * Let's create a new +TraversalDescription+ from the old one, * having +NODE_GLOBAL+ uniqueness to see the difference. * * TIP: The +TraversalDescription+ object is immutable, * so we have to use the new instance returned * with the new uniqueness setting. * * @@traverseNodeGlobal * * Now only one path is returned: * * @@outNodeGlobal */ @Graph({"Pet0 descendant Pet1", "Pet0 descendant Pet2", "Pet0 descendant Pet3", "Principal1 owns Pet1", "Principal2 owns Pet2", "Principal1 owns Pet3"}) @Test @Documented public void pathUniquenessExample() { Node start = data.get().get( "Pet0" ); gen.get().addSnippet( "graph", createGraphVizWithNodeId("Descendants Example Graph", graphdb(), gen.get().getTitle()) ); gen.get(); gen.get().addTestSourceSnippets( this.getClass(), "traverser", "traverseNodeGlobal" ); // START SNIPPET: traverser final Node target = data.get().get( "Principal1" ); TraversalDescription td = db.traversalDescription() .uniqueness( Uniqueness.NODE_PATH ) .evaluator( new Evaluator() { @Override public Evaluation evaluate( Path path ) { boolean endNodeIsTarget = path.endNode().equals( target ); return Evaluation.of( endNodeIsTarget, !endNodeIsTarget ); } } ); Traverser results = td.traverse( start ); // END SNIPPET: traverser String output = ""; int count = 0; //we should get two paths back, through Pet1 and Pet3 try ( Transaction ignore = db.beginTx() ) { for ( Path path : results ) { count++; output += path.toString() + "\n"; } } gen.get().addSnippet( "output", createOutputSnippet( output ) ); assertEquals( 2, count ); // START SNIPPET: traverseNodeGlobal TraversalDescription nodeGlobalTd = td.uniqueness( Uniqueness.NODE_GLOBAL ); results = nodeGlobalTd.traverse( start ); // END SNIPPET: traverseNodeGlobal String output2 = ""; count = 0; // we should get two paths back, through Pet1 and Pet3 try ( Transaction tx = db.beginTx() ) { for ( Path path : results ) { count++; output2 += path.toString() + "\n"; } } gen.get().addSnippet( "outNodeGlobal", createOutputSnippet( output2 ) ); assertEquals( 1, count ); } }
false
community_embedded-examples_src_test_java_org_neo4j_examples_UniquenessOfPathsDocTest.java
2,976
public class TraversalExample { private GraphDatabaseService db; private TraversalDescription friendsTraversal; public TraversalExample( GraphDatabaseService db ) { this.db = db; // START SNIPPET: basetraverser friendsTraversal = db.traversalDescription() .depthFirst() .relationships( Rels.KNOWS ) .uniqueness( Uniqueness.RELATIONSHIP_GLOBAL ); // END SNIPPET: basetraverser } public String knowsLikesTraverser( Node node ) { String output = ""; // START SNIPPET: knowslikestraverser for ( Path position : db.traversalDescription() .depthFirst() .relationships( Rels.KNOWS ) .relationships( Rels.LIKES, Direction.INCOMING ) .evaluator( Evaluators.toDepth( 5 ) ) .traverse( node ) ) { output += position + "\n"; } // END SNIPPET: knowslikestraverser return output; } public String traverseBaseTraverser( Node node ) { String output = ""; // START SNIPPET: traversebasetraverser for ( Path path : friendsTraversal.traverse( node ) ) { output += path + "\n"; } // END SNIPPET: traversebasetraverser return output; } public String depth3( Node node ) { String output = ""; // START SNIPPET: depth3 for ( Path path : friendsTraversal .evaluator( Evaluators.toDepth( 3 ) ) .traverse( node ) ) { output += path + "\n"; } // END SNIPPET: depth3 return output; } public String depth4( Node node ) { String output = ""; // START SNIPPET: depth4 for ( Path path : friendsTraversal .evaluator( Evaluators.fromDepth( 2 ) ) .evaluator( Evaluators.toDepth( 4 ) ) .traverse( node ) ) { output += path + "\n"; } // END SNIPPET: depth4 return output; } public String nodes( Node node ) { String output = ""; // START SNIPPET: nodes for ( Node currentNode : friendsTraversal .traverse( node ) .nodes() ) { output += currentNode.getProperty( "name" ) + "\n"; } // END SNIPPET: nodes return output; } public String relationships( Node node ) { String output = ""; // START SNIPPET: relationships for ( Relationship relationship : friendsTraversal .traverse( node ) .relationships() ) { output += relationship.getType().name() + "\n"; } // END SNIPPET: relationships return output; } // START SNIPPET: sourceRels private enum Rels implements RelationshipType { LIKES, KNOWS } // END SNIPPET: sourceRels }
false
community_embedded-examples_src_main_java_org_neo4j_examples_TraversalExample.java
2,977
public class TraversalDocTest extends ImpermanentGraphJavaDocTestBase { /** * A * http://components.neo4j.org/neo4j/{neo4j-version}/apidocs/org/neo4j/graphdb/traversal/TraversalDescription.html[traversal description] is built using a * fluent interface and such a description can then spawn * http://components.neo4j.org/neo4j/{neo4j-version}/apidocs/org/neo4j/graphdb/traversal/Traverser.html[traversers]. * * @@graph * * With the definition of the +RelationshipTypes+ as * * @@sourceRels * * The graph can be traversed with for example the following traverser, starting at the ``Joe'' node: * * @@knowslikestraverser * * The traversal will output: * * @@knowslikesoutput * * Since http://components.neo4j.org/neo4j/{neo4j-version}/apidocs/org/neo4j/graphdb/traversal/TraversalDescription.html[+TraversalDescription+]s * are immutable it is also useful to create template descriptions which holds common * settings shared by different traversals. For example, let's start with this traverser: * * @@basetraverser * * This traverser would yield the following output (we will keep starting from the ``Joe'' node): * * @@baseoutput * * Now let's create a new traverser from it, restricting depth to three: * * @@depth3 * * This will give us the following result: * * @@output3 * * Or how about from depth two to four? * That's done like this: * * @@depth4 * * This traversal gives us: * * @@output4 * * For various useful evaluators, see the * http://components.neo4j.org/neo4j/{neo4j-version}/apidocs/org/neo4j/graphdb/traversal/Evaluators.html[Evaluators] Java API * or simply implement the * http://components.neo4j.org/neo4j/{neo4j-version}/apidocs/org/neo4j/graphdb/traversal/Evaluator.html[Evaluator] interface yourself. * * If you're not interested in the http://components.neo4j.org/neo4j/{neo4j-version}/apidocs/org/neo4j/graphdb/Path.html[+Path+]s, * but the http://components.neo4j.org/neo4j/{neo4j-version}/apidocs/org/neo4j/graphdb/Node.html[+Node+]s * you can transform the traverser into an iterable of http://components.neo4j.org/neo4j/{neo4j-version}/apidocs/org/neo4j/graphdb/traversal/Traverser.html#nodes()[nodes] * like this: * * @@nodes * * In this case we use it to retrieve the names: * * @@nodeoutput * * http://components.neo4j.org/neo4j/{neo4j-version}/apidocs/org/neo4j/graphdb/traversal/Traverser.html#relationships()[Relationships] * are fine as well, here's how to get them: * * @@relationships * * Here the relationship types are written, and we get: * * @@relationshipoutput * * TIP: The source code for the traversers in this example is available at: * @@github */ @Test @Documented @Graph( { "Joe KNOWS Sara", "Lisa LIKES Joe", "Peter KNOWS Sara", "Dirk KNOWS Peter", "Lars KNOWS Dirk", "Ed KNOWS Lars", "Lisa KNOWS Lars" } ) public void how_to_use_the_Traversal_framework() { Node joe = data.get().get( "Joe" ); TraversalExample example = new TraversalExample( db ); gen.get().addSnippet( "graph", createGraphVizWithNodeId( "Traversal Example Graph", graphdb(), gen.get().getTitle() ) ); try ( Transaction tx = db.beginTx() ) { String output = example.knowsLikesTraverser( joe ); gen.get().addSnippet( "knowslikesoutput", createOutputSnippet( output ) ); output = example.traverseBaseTraverser( joe ); gen.get().addSnippet( "baseoutput", createOutputSnippet( output ) ); output = example.depth3( joe ); gen.get().addSnippet( "output3", createOutputSnippet( output ) ); output = example.depth4( joe ); gen.get().addSnippet( "output4", createOutputSnippet( output ) ); output = example.nodes( joe ); gen.get().addSnippet( "nodeoutput", createOutputSnippet( output ) ); output = example.relationships( joe ); gen.get().addSnippet( "relationshipoutput", createOutputSnippet( output ) ); gen.get().addSourceSnippets( example.getClass(), "knowslikestraverser", "sourceRels", "basetraverser", "depth3", "depth4", "nodes", "relationships" ); gen.get().addGithubSourceLink( "github", example.getClass(), "community/embedded-examples" ); } } }
false
community_embedded-examples_src_test_java_org_neo4j_examples_TraversalDocTest.java
2,978
public class StartWithConfigurationDocTest { @Test public void loadFromFile() { String pathToConfig = "src/test/resources/"; // START SNIPPET: startDbWithConfig GraphDatabaseService graphDb = new GraphDatabaseFactory() .newEmbeddedDatabaseBuilder( storeDir ) .loadPropertiesFromFile( pathToConfig + "neo4j.properties" ) .newGraphDatabase(); // END SNIPPET: startDbWithConfig assertNotNull( graphDb ); graphDb.shutdown(); } @Test public void loadFromHashmap() { // START SNIPPET: startDbWithMapConfig GraphDatabaseService graphDb = new GraphDatabaseFactory() .newEmbeddedDatabaseBuilder( storeDir ) .setConfig( GraphDatabaseSettings.nodestore_mapped_memory_size, "10M" ) .setConfig( GraphDatabaseSettings.string_block_size, "60" ) .setConfig( GraphDatabaseSettings.array_block_size, "300" ) .newGraphDatabase(); // END SNIPPET: startDbWithMapConfig assertNotNull( graphDb ); graphDb.shutdown(); } private final String storeDir = TargetDirectory.forTest( getClass() ).makeGraphDbDir().getAbsolutePath(); }
false
community_embedded-examples_src_test_java_org_neo4j_examples_StartWithConfigurationDocTest.java
2,979
public class RolesDocTest extends ImpermanentGraphJavaDocTestBase { private static final String NAME = "name"; public enum RoleRels implements RelationshipType { ROOT, PART_OF, MEMBER_OF } /** * This is an example showing a hierarchy of * roles. * What's interesting is that a tree is not sufficient for storing this kind of structure, * as elaborated below. * * image::roles.png[scaledwidth="100%"] * * This is an implementation of an example found in the article * http://www.codeproject.com/Articles/22824/A-Model-to-Represent-Directed-Acyclic-Graphs-DAG-o[A Model to Represent Directed Acyclic Graphs (DAG) on SQL Databases] * by http://www.codeproject.com/script/Articles/MemberArticles.aspx?amid=274518[Kemal Erdogan]. * The article discusses how to store http://en.wikipedia.org/wiki/Directed_acyclic_graph[ * directed acyclic graphs] (DAGs) * in SQL based DBs. DAGs are almost trees, but with a twist: it may be possible to reach * the same node through different paths. Trees are restricted from this possibility, which * makes them much easier to handle. In our case it is ``Ali'' and ``Engin'', * as they are both admins and users and thus reachable through these group nodes. * Reality often looks this way and can't be captured by tree structures. * * In the article an SQL Stored Procedure solution is provided. The main idea, * that also have some support from scientists, is to pre-calculate all possible (transitive) paths. * Pros and cons of this approach: * * * decent performance on read * * low performance on insert * * wastes _lots_ of space * * relies on stored procedures * * In Neo4j storing the roles is trivial. In this case we use +PART_OF+ (green edges) relationships * to model the group hierarchy and +MEMBER_OF+ (blue edges) to model membership in groups. * We also connect the top level groups to the reference node by +ROOT+ relationships. * This gives us a useful partitioning of the graph. Neo4j has no predefined relationship * types, you are free to create any relationship types and give them the semantics you want. * * Lets now have a look at how to retrieve information from the graph. The the queries are done using <<cypher-query-lang, Cypher>>, * the Java code is using the Neo4j Traversal API (see <<tutorial-traversal-java-api>>, which is part of <<advanced-usage>>). * * == Get the admins == * * In Cypher, we could get the admins like this: * * @@query-get-admins * * resulting in: * * @@o-query-get-admins * * And here's the code when using the Java Traversal API: * * @@get-admins * * resulting in the output * * @@o-get-admins * * The result is collected from the traverser using this code: * * @@read-traverser * * == Get the group memberships of a user == * * In Cypher: * * @@query-get-user-memberships * * @@o-query-get-user-memberships * * Using the Neo4j Java Traversal API, this query looks like: * * @@get-user-memberships * * resulting in: * * @@o-get-user-memberships * * == Get all groups == * * In Cypher: * * @@query-get-groups * * @@o-query-get-groups * * In Java: * * @@get-groups * * resulting in: * * @@o-get-groups * * == Get all members of all groups == * * Now, let's try to find all users in the system being part of any group. * * In Cypher, this looks like: * * @@query-get-members * * and results in the following output: * * @@o-query-get-members * * in Java: * * @@get-members * * @@o-get-members * * As seen above, querying even more complex scenarios can be done using comparatively short * constructs in Cypher or Java. */ @Test @Documented @Graph( { "Admins ROOT Reference_Node", "Users ROOT Reference_Node", "HelpDesk PART_OF Admins", "Managers PART_OF Users", "Technicians PART_OF Users", "ABCTechnicians PART_OF Technicians", "Ali MEMBER_OF Users", "Ali MEMBER_OF Admins", "Engin MEMBER_OF Users", "Engin MEMBER_OF HelpDesk", "Demet MEMBER_OF HelpDesk", "Burcu MEMBER_OF Users", "Can MEMBER_OF Users", "Gul MEMBER_OF Managers", "Fuat MEMBER_OF Managers", "Hakan MEMBER_OF Technicians", "Irmak MEMBER_OF Technicians", "Jale MEMBER_OF ABCTechnicians" } ) public void user_roles_in_graphs() { // get Admins gen.get() .addTestSourceSnippets( this.getClass(), "get-admins", "get-user-memberships", "get-groups", "get-members", "read-traverser" ); System.out.println( "All admins:" ); // START SNIPPET: get-admins Node admins = getNodeByName( "Admins" ); TraversalDescription traversalDescription = db.traversalDescription() .breadthFirst() .evaluator( Evaluators.excludeStartPosition() ) .relationships( RoleRels.PART_OF, Direction.INCOMING ) .relationships( RoleRels.MEMBER_OF, Direction.INCOMING ); Traverser traverser = traversalDescription.traverse( admins ); // END SNIPPET: get-admins try ( Transaction ignore = graphdb().beginTx() ) { gen.get().addSnippet( "o-get-admins", createOutputSnippet( traverserToString( traverser ) ) ); String query = "match ({name: 'Admins'})<-[:PART_OF*0..]-(group)<-[:MEMBER_OF]-(user) return user.name, group.name"; gen.get().addSnippet( "query-get-admins", createCypherSnippet( query ) ); String result = engine.execute( query ) .dumpToString(); assertTrue( result.contains("Engin") ); gen.get().addSnippet( "o-query-get-admins", createQueryResultSnippet( result ) ); //Jale's memberships // START SNIPPET: get-user-memberships Node jale = getNodeByName( "Jale" ); traversalDescription = db.traversalDescription() .depthFirst() .evaluator( Evaluators.excludeStartPosition() ) .relationships( RoleRels.MEMBER_OF, Direction.OUTGOING ) .relationships( RoleRels.PART_OF, Direction.OUTGOING ); traverser = traversalDescription.traverse( jale ); // END SNIPPET: get-user-memberships gen.get().addSnippet( "o-get-user-memberships", createOutputSnippet( traverserToString( traverser ) ) ); query = "match ({name: 'Jale'})-[:MEMBER_OF]->()-[:PART_OF*0..]->(group) return group.name"; gen.get().addSnippet( "query-get-user-memberships", createCypherSnippet( query ) ); result = engine.execute( query ) .dumpToString(); assertTrue( result.contains("Users") ); gen.get() .addSnippet( "o-query-get-user-memberships", createQueryResultSnippet( result ) ); // get all groups // START SNIPPET: get-groups Node referenceNode = getNodeByName( "Reference_Node") ; traversalDescription = db.traversalDescription() .breadthFirst() .evaluator( Evaluators.excludeStartPosition() ) .relationships( RoleRels.ROOT, Direction.INCOMING ) .relationships( RoleRels.PART_OF, Direction.INCOMING ); traverser = traversalDescription.traverse( referenceNode ); // END SNIPPET: get-groups gen.get().addSnippet( "o-get-groups", createOutputSnippet( traverserToString( traverser ) ) ); query = "match ({name: 'Reference_Node'})<-[:ROOT]->()<-[:PART_OF*0..]-(group) return group.name"; gen.get().addSnippet( "query-get-groups", createCypherSnippet( query ) ); result = engine.execute( query ) .dumpToString(); assertTrue( result.contains("Users") ); gen.get() .addSnippet( "o-query-get-groups", createQueryResultSnippet( result ) ); //get all members // START SNIPPET: get-members traversalDescription = db.traversalDescription() .breadthFirst() .evaluator( Evaluators.includeWhereLastRelationshipTypeIs( RoleRels.MEMBER_OF ) ); traverser = traversalDescription.traverse( referenceNode ); // END SNIPPET: get-members gen.get().addSnippet( "o-get-members", createOutputSnippet( traverserToString( traverser ) ) ); query = "match ({name: 'Reference_Node'})<-[:ROOT]->(root), p=(root)<-[PART_OF*0..]-()<-[:MEMBER_OF]-(user) " + "return user.name, min(length(p)) " + "order by min(length(p)), user.name"; gen.get().addSnippet( "query-get-members", createCypherSnippet( query ) ); result = engine.execute( query ) .dumpToString(); assertTrue( result.contains("Engin") ); gen.get() .addSnippet( "o-query-get-members", createQueryResultSnippet( result ) ); /* more advanced example query = "start refNode=node("+ referenceNode.getId() +") " + "match p=refNode<-[:ROOT]->parent<-[:PART_OF*0..]-group, group<-[:MEMBER_OF]-user return group.name, user.name, LENGTH(p) " + "order by LENGTH(p)"; */ } } private String traverserToString( Traverser traverser ) { // START SNIPPET: read-traverser String output = ""; for ( Path path : traverser ) { Node node = path.endNode(); output += "Found: " + node.getProperty( NAME ) + " at depth: " + ( path.length() - 1 ) + "\n"; } // END SNIPPET: read-traverser return output; } private Node getNodeByName( String string ) { return data.get().get( string ); } }
false
community_embedded-examples_src_test_java_org_neo4j_examples_RolesDocTest.java
2,980
public class Roles extends ImpermanentGraphJavaDocTestBase { private static final String NAME = "name"; public enum RoleRels implements RelationshipType { ROOT, PART_OF, MEMBER_OF } /** * This is an example showing a hierarchy of * roles. * What's interesting is that a tree is not sufficient for storing this structure, * as elaborated below. * * image::roles.png[scaledwidth="100%"] * * This is an implementation of an example found in the article * http://www.codeproject.com/Articles/22824/A-Model-to-Represent-Directed-Acyclic-Graphs-DAG-o[A Model to Represent Directed Acyclic Graphs (DAG) on SQL Databases] * by http://www.codeproject.com/script/Articles/MemberArticles.aspx?amid=274518[Kemal Erdogan]. * The article discusses how to store http://en.wikipedia.org/wiki/Directed_acyclic_graph[ * directed acyclic graphs] (DAGs) * in SQL based DBs. DAGs are almost trees, but with a twist: it may be possible to reach * the same node through different paths. Trees are restricted from this possibility, which * makes them much easier to handle. In our case it is "Ali" and "Engin", * as they are both admins and users and thus reachable through these group nodes. * Reality often looks this way and can't be captured by tree structures. * * In the article an SQL Stored Procedure solution is provided. The main idea, * that also have some support from scientists, is to pre-calculate all possible (transitive) paths. * Pros and cons of this approach: * * * decent performance on read * * low performance on insert * * wastes _lots_ of space * * relies on stored procedures * * In Neo4j storing the roles is trivial. In this case we use +PART_OF+ (green edges) relationships * to model the group hierarchy and +MEMBER_OF+ (blue edges) to model membership in groups. * We also connect the top level groups to a reference node by +ROOT+ relationships. * This gives us a useful partitioning of the graph. Neo4j has no predefined relationship * types, you are free to create any relationship types and give them any semantics you want. * * Lets now have a look at how to retrieve information from the graph. The Java code is using * the Neo4j Traversal API (see <<tutorial-traversal-java-api>>), the queries are done using <<cypher-query-lang, Cypher>>. * * == Get the admins == * * @@get-admins * * resulting in the output * * @@o-get-admins * * The result is collected from the traverser using this code: * * @@read-traverser * * In Cypher, a similar query would be: * * @@query-get-admins * * resulting in: * * @@o-query-get-admins * * == Get the group memberships of a user == * * Using the Neo4j Java Traversal API, this query looks like: * * @@get-user-memberships * * resuling in: * * @@o-get-user-memberships * * In Cypher: * * @@query-get-user-memberships * * @@o-query-get-user-memberships * * == Get all groups == * * In Java: * * @@get-groups * * resulting in: * * @@o-get-groups * * In Cypher: * * @@query-get-groups * * @@o-query-get-groups * * == Get all members of all groups == * * Now, let's try to find all users in the system being part of any group. * * in Java: * * @@get-members * * @@o-get-members * * In Cypher, this looks like: * * @@query-get-members * * and results in the following output: * * @@o-query-get-members * * As seen above, querying even more complex scenarios can be done using comparatively short * constructs in Java and other query mechanisms. */ @Test @Documented @Graph( { "Admins ROOT Reference_Node", "Users ROOT Reference_Node", "HelpDesk PART_OF Admins", "Managers PART_OF Users", "Technicians PART_OF Users", "ABCTechnicians PART_OF Technicians", "Ali MEMBER_OF Users", "Ali MEMBER_OF Admins", "Engin MEMBER_OF Users", "Engin MEMBER_OF HelpDesk", "Demet MEMBER_OF HelpDesk", "Burcu MEMBER_OF Users", "Can MEMBER_OF Users", "Gul MEMBER_OF Managers", "Fuat MEMBER_OF Managers", "Hakan MEMBER_OF Technicians", "Irmak MEMBER_OF Technicians", "Jale MEMBER_OF ABCTechnicians" } ) public void user_roles_in_graphs() { // get Admins gen.get() .addTestSourceSnippets( this.getClass(), "get-admins", "get-user-memberships", "get-groups", "get-members", "read-traverser" ); System.out.println( "All admins:" ); // START SNIPPET: get-admins Node admins = getNodeByName( "Admins" ); TraversalDescription traversal = db.traversalDescription() .breadthFirst() .evaluator( excludeStartPosition() ) .relationships( RoleRels.PART_OF, INCOMING ) .relationships( RoleRels.MEMBER_OF, INCOMING ); // END SNIPPET: get-admins gen.get().addSnippet( "o-get-admins", createOutputSnippet( traverserToString( traversal.traverse( admins ) ) ) ); String query = "start admins=node(" + admins.getId() + ") match admins<-[:PART_OF*0..]-group<-[:MEMBER_OF]-user return user.name, group.name"; gen.get().addSnippet( "query-get-admins", createCypherSnippet( query ) ); String result = engine.execute( query ) .dumpToString(); assertTrue( result.contains("Engin") ); gen.get().addSnippet( "o-query-get-admins", createQueryResultSnippet( result ) ); //Jale's memberships // START SNIPPET: get-user-memberships Node jale = getNodeByName( "Jale" ); traversal = db.traversalDescription() .depthFirst() .evaluator( excludeStartPosition() ) .relationships( RoleRels.MEMBER_OF, OUTGOING ) .relationships( RoleRels.PART_OF, OUTGOING ); // END SNIPPET: get-user-memberships gen.get().addSnippet( "o-get-user-memberships", createOutputSnippet( traverserToString( traversal.traverse( jale ) ) ) ); query = "start jale=node(" + jale.getId() + ") match jale-[:MEMBER_OF]->()-[:PART_OF*0..]->group return group.name"; gen.get().addSnippet( "query-get-user-memberships", createCypherSnippet( query ) ); result = engine.execute( query ) .dumpToString(); assertTrue( result.contains("Users") ); gen.get() .addSnippet( "o-query-get-user-memberships", createQueryResultSnippet( result ) ); // get all groups // START SNIPPET: get-groups Node referenceNode = getNodeByName( "Reference_Node") ; traversal = db.traversalDescription() .breadthFirst() .evaluator( excludeStartPosition() ) .relationships( RoleRels.ROOT, INCOMING ) .relationships( RoleRels.PART_OF, INCOMING ); // END SNIPPET: get-groups gen.get().addSnippet( "o-get-groups", createOutputSnippet( traverserToString( traversal.traverse( referenceNode ) ) ) ); query = "start refNode=node(" + referenceNode.getId() + ") match refNode<-[:ROOT]->()<-[:PART_OF*0..]-group return group.name"; gen.get().addSnippet( "query-get-groups", createCypherSnippet( query ) ); result = engine.execute( query ) .dumpToString(); assertTrue( result.contains("Users") ); gen.get() .addSnippet( "o-query-get-groups", createQueryResultSnippet( result ) ); //get all members // START SNIPPET: get-members traversal = db.traversalDescription() .breadthFirst() .evaluator( Evaluators.includeWhereLastRelationshipTypeIs( RoleRels.MEMBER_OF ) ) .relationships( RoleRels.ROOT, INCOMING ) .relationships( RoleRels.PART_OF, INCOMING ) .relationships( RoleRels.MEMBER_OF, INCOMING ); // END SNIPPET: get-members gen.get().addSnippet( "o-get-members", createOutputSnippet( traverserToString( traversal.traverse( referenceNode ) ) ) ); query = "start refNode=node("+ referenceNode.getId() +") " + "match refNode<-[:ROOT]->root, p=root<-[PART_OF*0..]-()<-[:MEMBER_OF]-user " + "return user.name, min(length(p)) " + "order by min(length(p)), user.name"; gen.get().addSnippet( "query-get-members", createCypherSnippet( query ) ); result = engine.execute( query ) .dumpToString(); assertTrue( result.contains("Engin") ); gen.get() .addSnippet( "o-query-get-members", createQueryResultSnippet( result ) ); /* more advanced example query = "start refNode=node("+ referenceNode.getId() +") " + "match p=refNode<-[:ROOT]->parent<-[:PART_OF*0..]-group, group<-[:MEMBER_OF]-user return group.name, user.name, LENGTH(p) " + "order by LENGTH(p)"; */ } private String traverserToString( Traverser traverser ) { try ( Transaction ignore = db.beginTx() ) { // START SNIPPET: read-traverser String output = ""; for ( Path path : traverser ) { output += "Found: " + path.endNode().getProperty( NAME ) + " at depth: " + path.length() + "\n"; } // END SNIPPET: read-traverser return output; } } private Node getNodeByName( String string ) { return data.get().get( string ); } }
false
community_embedded-examples_src_test_java_org_neo4j_examples_Roles.java
2,981
public class ReadOnlyDocTest { protected GraphDatabaseService graphDb; /** * Create read only database. */ @Before public void prepareReadOnlyDatabase() throws IOException { File dir = new File( "target/read-only-db/location" ); if ( dir.exists() ) { FileUtils.deleteRecursively( dir ); } new GraphDatabaseFactory().newEmbeddedDatabase( "target/read-only-db/location" ) .shutdown(); // START SNIPPET: createReadOnlyInstance graphDb = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder( "target/read-only-db/location" ) .setConfig( GraphDatabaseSettings.read_only, "true" ) .newGraphDatabase(); // END SNIPPET: createReadOnlyInstance } /** * Shutdown the database. */ @After public void shutdownDatabase() { graphDb.shutdown(); } @Test public void makeSureDbIsOnlyReadable() { // when try (Transaction tx = graphDb.beginTx()) { graphDb.createNode(); fail("expected exception"); } // then catch ( ReadOnlyDbException e ) { // ok } } }
false
community_embedded-examples_src_test_java_org_neo4j_examples_ReadOnlyDocTest.java
2,982
{ @Override public Double getCost( final Node node, final Node goal ) { double dx = (Double) node.getProperty( "x" ) - (Double) goal.getProperty( "x" ); double dy = (Double) node.getProperty( "y" ) - (Double) goal.getProperty( "y" ); double result = Math.sqrt( Math.pow( dx, 2 ) + Math.pow( dy, 2 ) ); return result; } };
false
community_embedded-examples_src_test_java_org_neo4j_examples_PathFindingDocTest.java
2,983
public class PathFindingDocTest { private static GraphDatabaseService graphDb; private Transaction tx; private static enum ExampleTypes implements RelationshipType { MY_TYPE } @BeforeClass public static void startDb() { String storeDir = TargetDirectory.forTest( PathFindingDocTest.class ).makeGraphDbDir().getAbsolutePath(); deleteFileOrDirectory( new File( storeDir ) ); graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( storeDir ); } @Before public void doBefore() { tx = graphDb.beginTx(); } @After public void doAfter() { tx.success(); tx.close(); } @AfterClass public static void shutdownDb() { try { if ( graphDb != null ) graphDb.shutdown(); } finally { graphDb = null; } } @Test public void shortestPathExample() { // START SNIPPET: shortestPathUsage Node startNode = graphDb.createNode(); Node middleNode1 = graphDb.createNode(); Node middleNode2 = graphDb.createNode(); Node middleNode3 = graphDb.createNode(); Node endNode = graphDb.createNode(); createRelationshipsBetween( startNode, middleNode1, endNode ); createRelationshipsBetween( startNode, middleNode2, middleNode3, endNode ); // Will find the shortest path between startNode and endNode via // "MY_TYPE" relationships (in OUTGOING direction), like f.ex: // // (startNode)-->(middleNode1)-->(endNode) // PathFinder<Path> finder = GraphAlgoFactory.shortestPath( PathExpanders.forTypeAndDirection( ExampleTypes.MY_TYPE, Direction.OUTGOING ), 15 ); Iterable<Path> paths = finder.findAllPaths( startNode, endNode ); // END SNIPPET: shortestPathUsage Path path = paths.iterator().next(); assertEquals( 2, path.length() ); assertEquals( startNode, path.startNode() ); assertEquals( endNode, path.endNode() ); Iterator<Node> iterator = path.nodes().iterator(); iterator.next(); assertEquals( middleNode1, iterator.next() ); } private void createRelationshipsBetween( final Node... nodes ) { for ( int i = 0; i < nodes.length - 1; i++ ) { nodes[i].createRelationshipTo( nodes[i+1], ExampleTypes.MY_TYPE ); } } @Test public void dijkstraUsage() { Node node1 = graphDb.createNode(); Node node2 = graphDb.createNode(); Relationship rel = node1.createRelationshipTo( node2, ExampleTypes.MY_TYPE ); rel.setProperty( "cost", 1d ); findCheapestPathWithDijkstra( node1, node2 ); } public WeightedPath findCheapestPathWithDijkstra( final Node nodeA, final Node nodeB ) { // START SNIPPET: dijkstraUsage PathFinder<WeightedPath> finder = GraphAlgoFactory.dijkstra( PathExpanders.forTypeAndDirection( ExampleTypes.MY_TYPE, Direction.BOTH ), "cost" ); WeightedPath path = finder.findSinglePath( nodeA, nodeB ); // Get the weight for the found path path.weight(); // END SNIPPET: dijkstraUsage return path; } private Node createNode( final Object... properties ) { return setProperties( graphDb.createNode(), properties ); } private <T extends PropertyContainer> T setProperties( final T entity, final Object[] properties ) { for ( int i = 0; i < properties.length; i++ ) { String key = properties[i++].toString(); Object value = properties[i]; entity.setProperty( key, value ); } return entity; } private Relationship createRelationship( final Node start, final Node end, final Object... properties ) { return setProperties( start.createRelationshipTo( end, ExampleTypes.MY_TYPE ), properties ); } @SuppressWarnings( "unused" ) @Test public void astarExample() { // START SNIPPET: astarUsage Node nodeA = createNode( "name", "A", "x", 0d, "y", 0d ); Node nodeB = createNode( "name", "B", "x", 7d, "y", 0d ); Node nodeC = createNode( "name", "C", "x", 2d, "y", 1d ); Relationship relAB = createRelationship( nodeA, nodeC, "length", 2d ); Relationship relBC = createRelationship( nodeC, nodeB, "length", 3d ); Relationship relAC = createRelationship( nodeA, nodeB, "length", 10d ); EstimateEvaluator<Double> estimateEvaluator = new EstimateEvaluator<Double>() { @Override public Double getCost( final Node node, final Node goal ) { double dx = (Double) node.getProperty( "x" ) - (Double) goal.getProperty( "x" ); double dy = (Double) node.getProperty( "y" ) - (Double) goal.getProperty( "y" ); double result = Math.sqrt( Math.pow( dx, 2 ) + Math.pow( dy, 2 ) ); return result; } }; PathFinder<WeightedPath> astar = GraphAlgoFactory.aStar( PathExpanders.allTypesAndDirections(), CommonEvaluators.doubleCostEvaluator( "length" ), estimateEvaluator ); WeightedPath path = astar.findSinglePath( nodeA, nodeB ); // END SNIPPET: astarUsage } public static void deleteFileOrDirectory( File file ) { if ( !file.exists() ) { return; } if ( file.isDirectory() ) { for ( File child : file.listFiles() ) { deleteFileOrDirectory( child ); } } else { file.delete(); } } }
false
community_embedded-examples_src_test_java_org_neo4j_examples_PathFindingDocTest.java
2,984
{ @Override public void run() { graphDb.shutdown(); } } );
false
community_embedded-examples_src_main_java_org_neo4j_examples_NewMatrix.java
2,985
public class NewMatrix { public enum RelTypes implements RelationshipType { NEO_NODE, KNOWS, CODED_BY } private static final String MATRIX_DB = "target/matrix-new-db"; private GraphDatabaseService graphDb; private long matrixNodeId; public static void main( String[] args ) { NewMatrix matrix = new NewMatrix(); matrix.setUp(); System.out.println( matrix.printNeoFriends() ); System.out.println( matrix.printMatrixHackers() ); matrix.shutdown(); } public void setUp() { deleteFileOrDirectory( new File( MATRIX_DB ) ); graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( MATRIX_DB ); registerShutdownHook(); createNodespace(); } public void shutdown() { graphDb.shutdown(); } public void createNodespace() { try ( Transaction tx = graphDb.beginTx() ) { // Create matrix node Node matrix = graphDb.createNode(); matrixNodeId = matrix.getId(); // Create Neo Node thomas = graphDb.createNode(); thomas.setProperty( "name", "Thomas Anderson" ); thomas.setProperty( "age", 29 ); // connect Neo/Thomas to the matrix node matrix.createRelationshipTo( thomas, RelTypes.NEO_NODE ); Node trinity = graphDb.createNode(); trinity.setProperty( "name", "Trinity" ); Relationship rel = thomas.createRelationshipTo( trinity, RelTypes.KNOWS ); rel.setProperty( "age", "3 days" ); Node morpheus = graphDb.createNode(); morpheus.setProperty( "name", "Morpheus" ); morpheus.setProperty( "rank", "Captain" ); morpheus.setProperty( "occupation", "Total badass" ); thomas.createRelationshipTo( morpheus, RelTypes.KNOWS ); rel = morpheus.createRelationshipTo( trinity, RelTypes.KNOWS ); rel.setProperty( "age", "12 years" ); Node cypher = graphDb.createNode(); cypher.setProperty( "name", "Cypher" ); cypher.setProperty( "last name", "Reagan" ); trinity.createRelationshipTo( cypher, RelTypes.KNOWS ); rel = morpheus.createRelationshipTo( cypher, RelTypes.KNOWS ); rel.setProperty( "disclosure", "public" ); Node smith = graphDb.createNode(); smith.setProperty( "name", "Agent Smith" ); smith.setProperty( "version", "1.0b" ); smith.setProperty( "language", "C++" ); rel = cypher.createRelationshipTo( smith, RelTypes.KNOWS ); rel.setProperty( "disclosure", "secret" ); rel.setProperty( "age", "6 months" ); Node architect = graphDb.createNode(); architect.setProperty( "name", "The Architect" ); smith.createRelationshipTo( architect, RelTypes.CODED_BY ); tx.success(); } } /** * Get the Neo node. (a.k.a. Thomas Anderson node) * * @return the Neo node */ private Node getNeoNode() { return graphDb.getNodeById( matrixNodeId ) .getSingleRelationship( RelTypes.NEO_NODE, Direction.OUTGOING ) .getEndNode(); } public String printNeoFriends() { try ( Transaction tx = graphDb.beginTx() ) { Node neoNode = getNeoNode(); // START SNIPPET: friends-usage int numberOfFriends = 0; String output = neoNode.getProperty( "name" ) + "'s friends:\n"; Traverser friendsTraverser = getFriends( neoNode ); for ( Path friendPath : friendsTraverser ) { output += "At depth " + friendPath.length() + " => " + friendPath.endNode() .getProperty( "name" ) + "\n"; numberOfFriends++; } output += "Number of friends found: " + numberOfFriends + "\n"; // END SNIPPET: friends-usage return output; } } // START SNIPPET: get-friends private static Traverser getFriends( final Node person ) { TraversalDescription td = Traversal.description() .breadthFirst() .relationships( RelTypes.KNOWS, Direction.OUTGOING ) .evaluator( Evaluators.excludeStartPosition() ); return td.traverse( person ); } // END SNIPPET: get-friends public String printMatrixHackers() { try ( Transaction tx = graphDb.beginTx() ) { // START SNIPPET: find--hackers-usage String output = "Hackers:\n"; int numberOfHackers = 0; Traverser traverser = findHackers( getNeoNode() ); for ( Path hackerPath : traverser ) { output += "At depth " + hackerPath.length() + " => " + hackerPath.endNode() .getProperty( "name" ) + "\n"; numberOfHackers++; } output += "Number of hackers found: " + numberOfHackers + "\n"; // END SNIPPET: find--hackers-usage return output; } } // START SNIPPET: find-hackers private static Traverser findHackers( final Node startNode ) { TraversalDescription td = Traversal.description() .breadthFirst() .relationships( RelTypes.CODED_BY, Direction.OUTGOING ) .relationships( RelTypes.KNOWS, Direction.OUTGOING ) .evaluator( Evaluators.includeWhereLastRelationshipTypeIs( RelTypes.CODED_BY ) ); return td.traverse( startNode ); } // END SNIPPET: find-hackers private void registerShutdownHook() { // Registers a shutdown hook for the Neo4j instance so that it // shuts down nicely when the VM exits (even if you "Ctrl-C" the // running example before it's completed) Runtime.getRuntime() .addShutdownHook( new Thread() { @Override public void run() { graphDb.shutdown(); } } ); } private static void deleteFileOrDirectory( final File file ) { if ( !file.exists() ) { return; } if ( file.isDirectory() ) { for ( File child : file.listFiles() ) { deleteFileOrDirectory( child ); } } else { file.delete(); } } }
false
community_embedded-examples_src_main_java_org_neo4j_examples_NewMatrix.java
2,986
{ @Override public void run() { shutdown(); } } );
false
community_embedded-examples_src_main_java_org_neo4j_examples_Neo4jShell.java
2,987
public class Neo4jShell { private static final String DB_PATH = "neo4j-store"; private static final String USERNAME_KEY = "username"; private static GraphDatabaseAPI graphDb; private static enum RelTypes implements RelationshipType { USERS_REFERENCE, USER, KNOWS, } public static void main( final String[] args ) throws Exception { registerShutdownHookForNeo(); boolean trueForLocal = waitForUserInput( "Would you like to start a " + "local shell instance or enable neo4j to accept remote " + "connections [l/r]? " ).equalsIgnoreCase( "l" ); if ( trueForLocal ) { startLocalShell(); } else { startRemoteShellAndWait(); } shutdown(); } private static void startLocalShell() throws Exception { graphDb = (GraphDatabaseAPI) new GraphDatabaseFactory().newEmbeddedDatabase( DB_PATH ); createExampleGraph(); ShellServer shellServer = new GraphDatabaseShellServer( graphDb ); ShellLobby.newClient( shellServer ).grabPrompt(); shellServer.shutdown(); } private static void startRemoteShellAndWait() throws Exception { graphDb = (GraphDatabaseAPI) new GraphDatabaseFactory().newEmbeddedDatabaseBuilder( DB_PATH ). setConfig( ShellSettings.remote_shell_enabled, Settings.TRUE ). newGraphDatabase(); createExampleGraph(); waitForUserInput( "Remote shell enabled, connect to it by executing\n" + "the shell-client script in a separate terminal." + "The script is located in the bin directory.\n" + "\nWhen you're done playing around, just press [Enter] " + "in this terminal " ); } private static String waitForUserInput( final String textToSystemOut ) throws Exception { System.out.print( textToSystemOut ); return new BufferedReader( new InputStreamReader( System.in, "UTF-8" ) ) .readLine(); } private static void createExampleGraph() { try ( Transaction tx = graphDb.beginTx() ) { // Create users type node System.out.println( "Creating example graph ..." ); Random random = new Random(); Node usersReferenceNode = graphDb.createNode(); Index<Node> references = graphDb.index().forNodes( "references" ); usersReferenceNode.setProperty( "reference", "users" ); references.add( usersReferenceNode, "reference", "users" ); // Create some users and index their names with the IndexService List<Node> users = new ArrayList<Node>(); for ( int id = 0; id < 100; id++ ) { Node userNode = createUser( formUserName( id ) ); usersReferenceNode.createRelationshipTo( userNode, RelTypes.USER ); if ( id > 10 ) { int numberOfFriends = random.nextInt( 5 ); Set<Node> knows = new HashSet<Node>(); for ( int i = 0; i < numberOfFriends; i++ ) { Node friend = users .get( random.nextInt( users.size() ) ); if ( knows.add( friend ) ) { userNode.createRelationshipTo( friend, RelTypes.KNOWS ); } } } users.add( userNode ); } tx.success(); } } private static void deleteExampleNodeSpace() { try ( Transaction tx = graphDb.beginTx() ) { // Delete the persons and remove them from the index System.out.println( "Deleting example graph ..." ); Node usersReferenceNode = graphDb.index().forNodes( "references" ).get( "reference", "users" ).getSingle(); for ( Relationship relationship : usersReferenceNode .getRelationships( RelTypes.USER, Direction.OUTGOING ) ) { Node user = relationship.getEndNode(); for ( Relationship knowsRelationship : user .getRelationships( RelTypes.KNOWS ) ) { knowsRelationship.delete(); } user.delete(); relationship.delete(); } usersReferenceNode.getSingleRelationship( RelTypes.USERS_REFERENCE, Direction.INCOMING ).delete(); usersReferenceNode.delete(); tx.success(); } } private static void shutdownGraphDb() { System.out.println( "Shutting down database ..." ); graphDb.shutdown(); graphDb = null; } private static void shutdown() { if ( graphDb != null ) { deleteExampleNodeSpace(); shutdownGraphDb(); } } private static void registerShutdownHookForNeo() { // Registers a shutdown hook for the Neo4j instance so that it // shuts down nicely when the VM exits (even if you "Ctrl-C" the // running example before it's completed) Runtime.getRuntime().addShutdownHook( new Thread() { @Override public void run() { shutdown(); } } ); } private static String formUserName( final int id ) { return "user" + id + "@neo4j.org"; } private static Node createUser( final String username ) { Node node = graphDb.createNode(); node.setProperty( USERNAME_KEY, username ); return node; } }
false
community_embedded-examples_src_main_java_org_neo4j_examples_Neo4jShell.java
2,988
public class Neo4jBasicDocTest { protected GraphDatabaseService graphDb; /** * Create temporary database for each unit test. */ // START SNIPPET: beforeTest @Before public void prepareTestDatabase() { graphDb = new TestGraphDatabaseFactory().newImpermanentDatabase(); } // END SNIPPET: beforeTest /** * Shutdown the database. */ // START SNIPPET: afterTest @After public void destroyTestDatabase() { graphDb.shutdown(); } // END SNIPPET: afterTest @Test public void startWithConfiguration() { // START SNIPPET: startDbWithConfig GraphDatabaseService db = new TestGraphDatabaseFactory() .newImpermanentDatabaseBuilder() .setConfig( GraphDatabaseSettings.nodestore_mapped_memory_size, "10M" ) .setConfig( GraphDatabaseSettings.string_block_size, "60" ) .setConfig( GraphDatabaseSettings.array_block_size, "300" ) .newGraphDatabase(); // END SNIPPET: startDbWithConfig db.shutdown(); } @Test public void shouldCreateNode() { // START SNIPPET: unitTest Node n = null; try ( Transaction tx = graphDb.beginTx() ) { n = graphDb.createNode(); n.setProperty( "name", "Nancy" ); tx.success(); } // The node should have a valid id assertThat( n.getId(), is( greaterThan( -1L ) ) ); // Retrieve a node by using the id of the created node. The id's and // property should match. try ( Transaction tx = graphDb.beginTx() ) { Node foundNode = graphDb.getNodeById( n.getId() ); assertThat( foundNode.getId(), is( n.getId() ) ); assertThat( (String) foundNode.getProperty( "name" ), is( "Nancy" ) ); } // END SNIPPET: unitTest } }
false
community_embedded-examples_src_test_java_org_neo4j_examples_Neo4jBasicDocTest.java
2,989
public class MatrixDocTest { private static JavaDocsGenerator gen; @BeforeClass public static void setUpBeforeClass() throws Exception { gen = new JavaDocsGenerator( "matrix-traversal-java", "dev" ); } @Test public void matrix() throws Exception { Matrix matrix = new Matrix(); matrix.setUp(); String friends = matrix.printNeoFriends(); String hackers = matrix.printMatrixHackers(); matrix.shutdown(); check( friends, hackers ); gen.saveToFile( "friends", createOutputSnippet( friends ) ); gen.saveToFile( "hackers", createOutputSnippet( hackers ) ); } @Test public void newMatrix() throws Exception { NewMatrix newMatrix = new NewMatrix(); newMatrix.setUp(); String friends = newMatrix.printNeoFriends(); String hackers = newMatrix.printMatrixHackers(); newMatrix.shutdown(); check( friends, hackers ); gen.saveToFile( "new-friends", createOutputSnippet( friends ) ); gen.saveToFile( "new-hackers", createOutputSnippet( hackers ) ); } private void check( String friends, String hackers ) { assertTrue( friends.contains( "friends found: 4" ) ); assertTrue( friends.contains( "Trinity" ) ); assertTrue( friends.contains( "Morpheus" ) ); assertTrue( friends.contains( "Cypher" ) ); assertTrue( friends.contains( "Agent Smith" ) ); assertTrue( hackers.contains( "hackers found: 1" ) ); assertTrue( hackers.contains( "The Architect" ) ); } }
false
community_embedded-examples_src_test_java_org_neo4j_examples_MatrixDocTest.java
2,990
{ @Override public void run() { graphDb.shutdown(); } } );
false
community_embedded-examples_src_main_java_org_neo4j_examples_Matrix.java
2,991
{ @Override public boolean isReturnableNode( final TraversalPosition currentPos ) { return !currentPos.isStartNode() && currentPos.lastRelationshipTraversed() .isType( RelTypes.CODED_BY ); } }, RelTypes.CODED_BY, Direction.OUTGOING, RelTypes.KNOWS,
false
community_embedded-examples_src_main_java_org_neo4j_examples_Matrix.java
2,992
{ @Override public Evaluation evaluate( final Path path ) { if ( path.length() == 0 ) { return Evaluation.EXCLUDE_AND_CONTINUE; } RelationshipType expectedType = orderedPathContext.get( path.length() - 1 ); boolean isExpectedType = path.lastRelationship() .isType( expectedType ); boolean included = path.length() == orderedPathContext.size() && isExpectedType; boolean continued = path.length() < orderedPathContext.size() && isExpectedType; return Evaluation.of( included, continued ); } } )
false
community_embedded-examples_src_main_java_org_neo4j_examples_orderedpath_OrderedPath.java
2,993
public class OrderedPathDocTest { private static OrderedPath orderedPath; private static JavaDocsGenerator gen; private static GraphDatabaseService db; @BeforeClass public static void setUp() throws IOException { File dir = new File( OrderedPath.DB_PATH ); if ( dir.exists() ) { FileUtils.deleteRecursively( dir ); } db = new TestGraphDatabaseFactory().newImpermanentDatabase(); orderedPath = new OrderedPath( db ); gen = new JavaDocsGenerator( "ordered-path-java", "dev" ); } @AfterClass public static void tearDown() { orderedPath.shutdownGraph(); } @Test public void testPath() { Node A = orderedPath.createTheGraph(); TraversalDescription traversalDescription = orderedPath.findPaths(); try ( Transaction tx = db.beginTx() ) { assertEquals( 1, count( traversalDescription.traverse( A ) ) ); } String output = orderedPath.printPaths( traversalDescription, A ); assertTrue( output.contains( "(A)--[REL1]-->(B)--[REL2]-->(C)--[REL3]-->(D)" ) ); String graph = AsciidocHelper.createGraphVizDeletingReferenceNode( "Ordered Path Graph", orderedPath.db, "java" ); assertFalse( graph.isEmpty() ); gen.saveToFile( "graph", graph ); gen.saveToFile( "output", createOutputSnippet( output ) ); } }
false
community_embedded-examples_src_test_java_org_neo4j_examples_orderedpath_OrderedPathDocTest.java
2,994
public class JmxDocTest { @Test public void readJmxProperties() { GraphDatabaseService graphDbService = new TestGraphDatabaseFactory().newImpermanentDatabase(); try { Date startTime = getStartTimeFromManagementBean( graphDbService ); Date now = new Date(); assertTrue( startTime.before( now ) || startTime.equals( now ) ); } finally { graphDbService.shutdown(); } } @Test public void properErrorOnNonStandardGraphDatabase() { GraphDatabaseService graphDbService = mock(GraphDatabaseService.class); try { getStartTimeFromManagementBean( graphDbService ); fail("Expected error"); } catch(IllegalArgumentException e) { assertEquals("Can only resolve object names for embedded Neo4j database " + "instances, eg. instances created by GraphDatabaseFactory or HighlyAvailableGraphDatabaseFactory.", e.getMessage()); } } // START SNIPPET: getStartTime private static Date getStartTimeFromManagementBean( GraphDatabaseService graphDbService ) { ObjectName objectName = JmxUtils.getObjectName( graphDbService, "Kernel" ); Date date = JmxUtils.getAttribute( objectName, "KernelStartTime" ); return date; } // END SNIPPET: getStartTime }
false
community_embedded-examples_src_test_java_org_neo4j_examples_JmxDocTest.java
2,995
public class AbstractPluginTestBase extends AbstractRestFunctionalTestBase { protected static FunctionalTestHelper functionalTestHelper; protected static GraphDbHelper helper; @BeforeClass public static void setupServer() throws IOException { functionalTestHelper = new FunctionalTestHelper( server() ); helper = functionalTestHelper.getGraphDbHelper(); } public void checkDatabaseLevelExtensionMetadata( Class<? extends ServerPlugin> klass, String name, String pattern ) throws Exception { Map<String, Object> map = getDatabaseLevelPluginMetadata( klass ); assertThat( (String) map.get( name ), RegExp.endsWith( String.format( pattern, klass.getSimpleName(), name ) ) ); } protected Map<String, Object> getDatabaseLevelPluginMetadata( Class<? extends ServerPlugin> klass ) throws JsonParseException { return getMetadata( klass, functionalTestHelper.dataUri() ); } protected Map<String, Object> getNodeLevelPluginMetadata( Class<? extends ServerPlugin> klass, long nodeId ) throws JsonParseException { return getMetadata( klass, functionalTestHelper.nodeUri( nodeId ) ); } @SuppressWarnings( "unchecked" ) private Map<String, Object> getMetadata( Class<? extends ServerPlugin> klass, String uri ) throws JsonParseException { Map<String, Object> map = PluginFunctionalTestHelper.makeGet( uri ); assertThat( "Could not get server metadata.", map, notNullValue() ); map = (Map<String, Object>) map.get( "extensions" ); assertThat( "Missing extensions key in server metadata.", map, notNullValue() ); map = (Map<String, Object>) map.get( klass.getSimpleName() ); assertThat( "Missing '" + klass.getSimpleName() + "' key in extensions.", map, notNullValue() ); return map; } protected String performPost( String uri ) { return performPost( uri, null ); } protected String performPost( String uri, String body ) { RESTDocsGenerator requestBuilder = gen.get() .noGraph() .expectedStatus( 200 ); if ( body != null ) { requestBuilder.payload( body ); } String result = requestBuilder .post( uri ) .entity(); return result; } }
false
community_server-examples_src_test_java_org_neo4j_examples_server_AbstractPluginTestBase.java
2,996
public class PersonRepository { private final GraphDatabaseService graphDb; private final Index<Node> index; private final Node personRefNode; public PersonRepository( GraphDatabaseService graphDb, Index<Node> index ) { this.graphDb = graphDb; this.index = index; personRefNode = getPersonsRootNode( graphDb ); } private Node getPersonsRootNode( GraphDatabaseService graphDb ) { Index<Node> referenceIndex = graphDb.index().forNodes( "reference"); IndexHits<Node> result = referenceIndex.get( "reference", "person" ); if (result.hasNext()) { return result.next(); } Node refNode = this.graphDb.createNode(); refNode.setProperty( "reference", "persons" ); referenceIndex.add( refNode, "reference", "persons" ); return refNode; } public Person createPerson( String name ) throws Exception { // to guard against duplications we use the lock grabbed on ref node // when // creating a relationship and are optimistic about person not existing Node newPersonNode = graphDb.createNode(); personRefNode.createRelationshipTo( newPersonNode, A_PERSON ); // lock now taken, we can check if already exist in index Node alreadyExist = index.get( Person.NAME, name ).getSingle(); if ( alreadyExist != null ) { throw new Exception( "Person with this name already exists " ); } newPersonNode.setProperty( Person.NAME, name ); index.add( newPersonNode, Person.NAME, name ); return new Person( newPersonNode ); } public Person getPersonByName( String name ) { Node personNode = index.get( Person.NAME, name ).getSingle(); if ( personNode == null ) { throw new IllegalArgumentException( "Person[" + name + "] not found" ); } return new Person( personNode ); } public void deletePerson( Person person ) { Node personNode = person.getUnderlyingNode(); index.remove( personNode, Person.NAME, person.getName() ); for ( Person friend : person.getFriends() ) { person.removeFriend( friend ); } personNode.getSingleRelationship( A_PERSON, Direction.INCOMING ).delete(); for ( StatusUpdate status : person.getStatus() ) { Node statusNode = status.getUnderlyingNode(); for ( Relationship r : statusNode.getRelationships() ) { r.delete(); } statusNode.delete(); } personNode.delete(); } public Iterable<Person> getAllPersons() { return new IterableWrapper<Person, Relationship>( personRefNode.getRelationships( A_PERSON ) ) { @Override protected Person underlyingObjectToObject( Relationship personRel ) { return new Person( personRel.getEndNode() ); } }; } }
false
community_embedded-examples_src_main_java_org_neo4j_examples_socnet_PersonRepository.java
2,997
private final class RankedPerson { final Person person; final int rank; private RankedPerson( Person person, int rank ) { this.person = person; this.rank = rank; } public Person getPerson() { return person; } public int getRank() { return rank; } }
false
community_embedded-examples_src_main_java_org_neo4j_examples_socnet_Person.java
2,998
private class RankedComparer implements Comparator<RankedPerson> { @Override public int compare( RankedPerson a, RankedPerson b ) { return b.getRank() - a.getRank(); } }
false
community_embedded-examples_src_main_java_org_neo4j_examples_socnet_Person.java
2,999
{ @Override protected Person underlyingObjectToObject( Node node ) { return new Person( node ); } };
false
community_embedded-examples_src_main_java_org_neo4j_examples_socnet_Person.java