Unnamed: 0
int64 0
6.7k
| func
stringlengths 12
89.6k
| target
bool 2
classes | project
stringlengths 45
151
|
|---|---|---|---|
2,800
|
path( RepresentationType.PATH )
{
@Override
public MappingRepresentation toRepresentation( Path position )
{
return new org.neo4j.server.rest.repr.PathRepresentation<Path>( position );
}
},
| false
|
community_server_src_main_java_org_neo4j_server_rest_domain_TraverserReturnType.java
|
2,801
|
relationship( RepresentationType.RELATIONSHIP )
{
@Override
public Representation toRepresentation( Path position )
{
Relationship lastRelationship = position.lastRelationship();
return lastRelationship != null? new org.neo4j.server.rest.repr.RelationshipRepresentation( lastRelationship ): Representation.emptyRepresentation();
}
},
| false
|
community_server_src_main_java_org_neo4j_server_rest_domain_TraverserReturnType.java
|
2,802
|
node( RepresentationType.NODE )
{
@Override
public MappingRepresentation toRepresentation( Path position )
{
return new org.neo4j.server.rest.repr.NodeRepresentation( position.endNode() );
}
},
| false
|
community_server_src_main_java_org_neo4j_server_rest_domain_TraverserReturnType.java
|
2,803
|
public class TraversalDescriptionBuilderTest
{
@Test(expected = IllegalArgumentException.class)
public void throwsIllegalArgumentOnUnknownExpanderType() throws Exception
{
// Given
TraversalDescriptionBuilder builder = new TraversalDescriptionBuilder( true );
Collection<Map<String,Object>> rels = new ArrayList<Map<String, Object>>();
rels.add( map( "type", "blah" ) );
// When
builder.from( map(
"relationships", rels,
"expander", "Suddenly, a string!" ) );
}
@Test(expected = IllegalArgumentException.class)
public void throwsIllegalArgumentOnNonStringExpanderType() throws Exception
{
// Given
TraversalDescriptionBuilder builder = new TraversalDescriptionBuilder( true );
Collection<Map<String,Object>> rels = new ArrayList<Map<String, Object>>();
rels.add( map( "type", "blah" ) );
// When
builder.from( map(
"relationships", rels,
"expander", map( ) ) );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_domain_TraversalDescriptionBuilderTest.java
|
2,804
|
public class TraversalDescriptionBuilder
{
private final EvaluatorFactory evaluatorFactory;
public TraversalDescriptionBuilder( boolean enableSandboxing )
{
this.evaluatorFactory = new EvaluatorFactory( enableSandboxing );
}
public TraversalDescription from( Map<String, Object> description )
{
try
{
TraversalDescription result = new MonoDirectionalTraversalDescription();
result = describeOrder( result, description );
result = describeUniqueness( result, description );
result = describeExpander( result, description );
result = describePruneEvaluator( result, description );
result = describeReturnFilter( result, description );
return result;
}
catch ( NoClassDefFoundError e )
{
// This one can happen if you run on Java 5, but haven't included
// the backported javax.script jar file(s) on the classpath.
throw new EvaluationException( e );
}
}
@SuppressWarnings( "unchecked" )
private TraversalDescription describeReturnFilter( TraversalDescription result,
Map<String, Object> description )
{
Object returnDescription = description.get( "return_filter" );
if ( returnDescription != null )
{
Evaluator filter = evaluatorFactory.returnFilter( (Map) returnDescription );
// Filter is null when "all" is used, no filter then
if ( filter != null )
{
result = result.evaluator( filter );
}
}
else
{
// Default return evaluator
result = result.evaluator( excludeStartPosition() );
}
return result;
}
@SuppressWarnings( "unchecked" )
private TraversalDescription describePruneEvaluator( TraversalDescription result,
Map<String, Object> description )
{
Object pruneDescription = description.get( "prune_evaluator" );
if ( pruneDescription != null )
{
Evaluator pruner = evaluatorFactory.pruneEvaluator( (Map) pruneDescription );
if ( pruner != null )
{
result = result.evaluator( pruner );
}
}
Object maxDepth = description.get( "max_depth" );
maxDepth = maxDepth != null || pruneDescription != null ? maxDepth : 1;
if ( maxDepth != null )
{
result = result.evaluator( Evaluators.toDepth( ((Number) maxDepth).intValue() ) );
}
return result;
}
@SuppressWarnings( "unchecked" )
private TraversalDescription describeExpander( TraversalDescription result,
Map<String, Object> description )
{
Object relationshipsDescription = description.get( "relationships" );
if ( relationshipsDescription != null )
{
Collection<Object> pairDescriptions;
if ( relationshipsDescription instanceof Collection )
{
pairDescriptions = (Collection<Object>) relationshipsDescription;
}
else
{
pairDescriptions = Arrays.asList( relationshipsDescription );
}
Expander expander = createExpander( description );
for ( Object pairDescription : pairDescriptions )
{
Map map = (Map) pairDescription;
String name = (String) map.get( "type" );
RelationshipType type = DynamicRelationshipType.withName( name );
String directionName = (String) map.get( "direction" );
expander = directionName == null ? expander.add( type ) :
expander.add( type, stringToEnum( directionName,
RelationshipDirection.class, true ).internal );
}
result = result.expand( expander );
}
return result;
}
private Expander createExpander( Map<String, Object> description )
{
if(description.containsKey( "expander" ))
{
Object expanderDesc = description.get( "expander" );
if(! (expanderDesc instanceof String))
{
throw new IllegalArgumentException( "Invalid expander type '"+expanderDesc+"', expected a string name." );
}
String expanderName = (String) expanderDesc;
if(expanderName.equalsIgnoreCase( "order_by_type" ))
{
return new OrderedByTypeExpander();
}
throw new IllegalArgumentException( "Unknown expander type: '"+expanderName+"'" );
}
// Default expander
return Traversal.emptyExpander();
}
private TraversalDescription describeUniqueness( TraversalDescription result, Map<String, Object> description )
{
Object uniquenessDescription = description.get( "uniqueness" );
if ( uniquenessDescription != null )
{
String name = null;
Object value = null;
if ( uniquenessDescription instanceof Map )
{
Map map = (Map) uniquenessDescription;
name = (String) map.get( "name" );
value = map.get( "value" );
}
else
{
name = (String) uniquenessDescription;
}
org.neo4j.kernel.Uniqueness uniqueness = stringToEnum( enumifyName( name ),
org.neo4j.kernel.Uniqueness.class, true );
result = value == null ? result.uniqueness( uniqueness ) : result.uniqueness( uniqueness, value );
}
return result;
}
private TraversalDescription describeOrder( TraversalDescription result, Map<String, Object> description )
{
String orderDescription = (String) description.get( "order" );
if ( orderDescription != null )
{
Order order = stringToEnum( enumifyName( orderDescription ), Order.class, true );
// TODO Fix
switch ( order )
{
case BREADTH_FIRST:
result = result.breadthFirst();
break;
case DEPTH_FIRST:
result = result.depthFirst();
break;
}
}
return result;
}
private <T extends Enum<T>> T stringToEnum( String name, Class<T> enumClass, boolean fuzzyMatch )
{
if ( name == null )
{
return null;
}
// name = enumifyName( name );
for ( T candidate : enumClass.getEnumConstants() )
{
if ( candidate.name()
.equals( name ) )
{
return candidate;
}
}
if ( fuzzyMatch )
{
for ( T candidate : enumClass.getEnumConstants() )
{
if ( candidate.name()
.startsWith( name ) )
{
return candidate;
}
}
}
throw new RuntimeException( "Unregognized " + enumClass.getSimpleName() + " '" + name + "'" );
}
private String enumifyName( String name )
{
return name.replaceAll( " ", "_" )
.toUpperCase();
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_domain_TraversalDescriptionBuilder.java
|
2,805
|
@SuppressWarnings( "serial" )
public class StartNodeSameAsEndNodeException extends Exception
{
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_domain_StartNodeSameAsEndNodeException.java
|
2,806
|
@SuppressWarnings( "serial" )
public class StartNodeNotFoundException extends Exception
{
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_domain_StartNodeNotFoundException.java
|
2,807
|
public class RelationshipExpanderBuilder
{
@SuppressWarnings( "unchecked" )
public static RelationshipExpander describeRelationships( Map<String, Object> description )
{
Expander expander = Traversal.emptyExpander();
Object relationshipsDescription = description.get( "relationships" );
if ( relationshipsDescription != null )
{
Collection<Object> pairDescriptions;
if ( relationshipsDescription instanceof Collection )
{
pairDescriptions = (Collection<Object>) relationshipsDescription;
}
else
{
pairDescriptions = Arrays.asList( relationshipsDescription );
}
for ( Object pairDescription : pairDescriptions )
{
Map map = (Map) pairDescription;
String name = (String) map.get( "type" );
RelationshipType type = DynamicRelationshipType.withName( name );
String directionName = (String) map.get( "direction" );
expander = ( directionName == null ) ? expander.add( type ) : expander.add( type,
stringToEnum( directionName, RelationshipDirection.class, true ).internal );
}
}
return expander;
}
// TODO Refactor - same method exists in TraversalDescriptionBuilder
private static <T extends Enum<T>> T stringToEnum( String name, Class<T> enumClass, boolean fuzzyMatch )
{
if ( name == null )
{
return null;
}
// name = enumifyName( name );
for ( T candidate : enumClass.getEnumConstants() )
{
if ( candidate.name()
.equals( name ) )
{
return candidate;
}
}
if ( fuzzyMatch )
{
for ( T candidate : enumClass.getEnumConstants() )
{
if ( candidate.name()
.startsWith( name ) )
{
return candidate;
}
}
}
throw new RuntimeException( "Unregognized " + enumClass.getSimpleName() + " '" + name + "'" );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_domain_RelationshipExpanderBuilder.java
|
2,808
|
public class PropertySettingStrategyTest
{
private static GraphDatabaseAPI db;
private Transaction tx;
private static PropertySettingStrategy propSetter;
@BeforeClass
public static void createDb()
{
db = (GraphDatabaseAPI) new TestGraphDatabaseFactory().newImpermanentDatabase();
propSetter = new PropertySettingStrategy( db );
}
@AfterClass
public static void closeDb()
{
db.shutdown();
}
@Before
public void beginTx()
{
tx = db.beginTx();
}
@After
public void rollbackTx()
{
tx.finish();
}
@Test
public void shouldSetSingleProperty() throws Exception
{
// Given
Node node = db.createNode();
// When
propSetter.setProperty( node, "name", "bob" );
// Then
assertThat( (String) node.getProperty( "name" ), is("bob"));
}
@Test
public void shouldSetMultipleProperties() throws Exception
{
// Given
Node node = db.createNode();
List<String> anArray = new ArrayList<String>( );
anArray.add( "hello" );
anArray.add( "Iamanarray" );
Map<String, Object> props = new HashMap<String, Object>();
props.put( "name", "bob" );
props.put( "age", 12 );
props.put( "anArray", anArray );
// When
propSetter.setProperties( node, props );
// Then
assertThat( (String) node.getProperty( "name" ), is("bob"));
assertThat( (Integer) node.getProperty( "age" ), is(12));
assertThat( (String[]) node.getProperty( "anArray" ), is(new String[]{"hello","Iamanarray"}));
}
@Test
public void shouldSetAllProperties() throws Exception
{
// Given
Node node = db.createNode();
node.setProperty( "name", "bob" );
node.setProperty( "age", 12 );
// When
propSetter.setAllProperties( node, map( "name", "Steven", "color", 123 ) );
// Then
assertThat( (String) node.getProperty( "name" ), is("Steven"));
assertThat( (Integer) node.getProperty( "color" ), is(123));
assertThat( node.hasProperty( "age" ), is(false));
}
// Handling empty collections
@Test
public void shouldNotFailSettingEmptyArrayIfEntityAlreadyHasAnEmptyArrayAsValue() throws Exception
{
// Given
Node node = db.createNode();
node.setProperty( "arr", new String[]{} );
// When
propSetter.setProperty( node, "arr", new ArrayList<Object>() );
// Then
assertThat( (String[]) node.getProperty( "arr" ), is(new String[]{}));
}
@Test
public void shouldNotFailSettingEmptyArrayAndOtherValuesIfEntityAlreadyHasAnEmptyArrayAsValue() throws Exception
{
// Given
Node node = db.createNode();
node.setProperty( "arr", new String[]{} );
Map<String, Object> props = new HashMap<String, Object>();
props.put( "name", "bob" );
props.put( "arr", new ArrayList<String>( ) );
// When
propSetter.setProperties( node, props );
// Then
assertThat( (String) node.getProperty( "name" ), is("bob"));
assertThat( (String[]) node.getProperty( "arr" ), is(new String[]{}));
}
@Test(expected = PropertyValueException.class)
public void shouldThrowPropertyErrorWhenSettingEmptyArrayOnEntityWithNoPreExistingProperty() throws Exception
{
// Given
Node node = db.createNode();
// When
propSetter.setProperty( node, "arr", new ArrayList<Object>() );
}
@Test(expected = PropertyValueException.class)
public void shouldThrowPropertyErrorWhenSettingEmptyArrayOnEntityWithNoPreExistingEmptyArray() throws Exception
{
// Given
Node node = db.createNode();
node.setProperty( "arr", "hello" );
// When
propSetter.setProperty( node, "arr", new ArrayList<Object>() );
}
@Test
public void shouldUseOriginalTypeWhenSettingEmptyArrayIfEntityAlreadyHasACollection() throws Exception
{
// Given
Node node = db.createNode();
node.setProperty( "arr", new String[]{"a","b"} );
// When
propSetter.setProperty( node, "arr", new ArrayList<Object>() );
// Then
assertThat( (String[]) node.getProperty( "arr" ), is(new String[]{}));
}
@Test
public void shouldUseOriginalTypeOnEmptyCollectionWhenSettingAllProperties() throws Exception
{
// Given
Node node = db.createNode();
node.setProperty( "name", "bob" );
node.setProperty( "arr", new String[]{"a","b"} );
// When
propSetter.setAllProperties( node, map("arr", new ArrayList<String>()) );
// Then
assertThat( node.hasProperty( "name" ), is(false));
assertThat( (String[]) node.getProperty( "arr" ), is(new String[]{}));
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_domain_PropertySettingStrategyTest.java
|
2,809
|
public class LeaseManagerTest
{
private static final long SIXTY_SECONDS = 60;
@Test
public void shouldNotAcceptLeasesWithNegativeTTL() throws Exception
{
FakeClock fakeClock = new FakeClock();
LeaseManager manager = new LeaseManager( fakeClock );
assertNull( manager.createLease( -1l, mock( PagedTraverser.class ) ) );
assertNull( manager.createLease( Long.MAX_VALUE + 1, mock( PagedTraverser.class ) ) );
}
@Test
public void shouldRetrieveAnExistingLeaseImmediatelyAfterCreation() throws Exception
{
FakeClock fakeClock = new FakeClock();
LeaseManager manager = new LeaseManager( fakeClock );
Lease lease = manager.createLease( SIXTY_SECONDS, mock( PagedTraverser.class ) );
assertNotNull( manager.getLeaseById( lease.getId() ) );
}
@Test
public void shouldRetrieveAnExistingLeaseSomeTimeAfterCreation() throws Exception
{
FakeClock fakeClock = new FakeClock();
LeaseManager manager = new LeaseManager( fakeClock );
Lease lease = manager.createLease( 120, mock( PagedTraverser.class ) );
fakeClock.forward( 1, TimeUnit.MINUTES );
assertNotNull( manager.getLeaseById( lease.getId() ) );
}
@Test
public void shouldNotRetrieveALeaseAfterItExpired() throws Exception
{
FakeClock fakeClock = new FakeClock();
LeaseManager manager = new LeaseManager( fakeClock );
Lease lease = manager.createLease( SIXTY_SECONDS, mock( PagedTraverser.class ) );
fakeClock.forward( 2, TimeUnit.MINUTES );
assertNull( manager.getLeaseById( lease.getId() ) );
}
@Test
public void shouldNotBarfWhenAnotherThreadOrRetrieveRevokesTheLease() throws Exception
{
FakeClock fakeClock = new FakeClock();
LeaseManager manager = new LeaseManager( fakeClock );
Lease leaseA = manager.createLease( SIXTY_SECONDS, mock( PagedTraverser.class ) );
Lease leaseB = manager.createLease( SIXTY_SECONDS * 3, mock( PagedTraverser.class ) );
fakeClock.forward( 2, TimeUnit.MINUTES );
assertNotNull( manager.getLeaseById( leaseB.getId() ) );
assertNull( manager.getLeaseById( leaseA.getId() ) );
}
@Test
public void shouldRemoveALease()
{
FakeClock fakeClock = new FakeClock();
LeaseManager manager = new LeaseManager( fakeClock );
Lease lease = manager.createLease( 101l, mock( PagedTraverser.class ) );
manager.remove( lease.getId() );
assertNull( manager.getLeaseById( lease.getId() ) );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_paging_LeaseManagerTest.java
|
2,810
|
public class PagedTraverser implements Iterator<List<Path>>, Iterable<List<Path>>, Leasable
{
private final int pageSize;
private final Traverser traverser;
private Iterator<Path> iterator;
public PagedTraverser( Traverser traverser, int pageSize )
{
this.traverser = traverser;
this.pageSize = pageSize;
}
@Override
public List<Path> next()
{
ensureIteratorStarted();
if ( !iterator.hasNext() )
{
return null;
}
List<Path> result = new ArrayList<>();
for ( int i = 0; i < pageSize; i++ )
{
if ( !iterator.hasNext() )
{
break;
}
result.add( iterator.next() );
}
return result;
}
private void ensureIteratorStarted()
{
if ( iterator == null )
{
iterator = traverser.iterator();
}
}
@Override
public boolean hasNext()
{
ensureIteratorStarted();
return iterator.hasNext();
}
@Override
public void remove()
{
iterator.remove();
}
@Override
public Iterator<List<Path>> iterator()
{
return this;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_paging_PagedTraverser.java
|
2,811
|
@SuppressWarnings( "serial" )
public class JsonParseException extends org.neo4j.server.rest.web.PropertyValueException
{
public JsonParseException( String message, Throwable cause )
{
super( message, cause );
}
public JsonParseException( String message )
{
super( message );
}
public JsonParseException( Throwable cause )
{
super( cause );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_domain_JsonParseException.java
|
2,812
|
public class PagedTraverserDocIT extends ExclusiveServerTestBase
{
private static CommunityNeoServer server;
private static FunctionalTestHelper functionalTestHelper;
private Node theStartNode;
private static final String PAGED_TRAVERSE_LINK_REL = "paged_traverse";
private static final int SHORT_LIST_LENGTH = 33;
private static final int LONG_LIST_LENGTH = 444;
@ClassRule
public static TemporaryFolder staticFolder = new TemporaryFolder();
public
@Rule
TestData<RESTDocsGenerator> gen = TestData.producedThrough( RESTDocsGenerator.PRODUCER );
private static FakeClock clock;
@Before
public void setUp()
{
gen.get().setSection( "dev/rest-api" );
}
@BeforeClass
public static void setupServer() throws Exception
{
clock = new FakeClock();
server = CommunityServerBuilder.server()
.usingDatabaseDir( staticFolder.getRoot().getAbsolutePath() )
.withClock( clock )
.build();
muteAll().call( new Callable<Void>()
{
@Override
public Void call() throws Exception
{
server.start();
return null;
}
} );
functionalTestHelper = new FunctionalTestHelper( server );
}
@Before
public void setupTheDatabase() throws Exception
{
ServerHelper.cleanTheDatabase( server );
}
@AfterClass
public static void stopServer() throws Exception
{
muteAll().call( new Callable<Void>()
{
@Override
public Void call() throws Exception
{
server.stop();
return null;
}
} );
}
@Test
public void nodeRepresentationShouldHaveLinkToPagedTraverser() throws Exception
{
theStartNode = createLinkedList( SHORT_LIST_LENGTH, server.getDatabase() );
JaxRsResponse response = RestRequest.req().get( functionalTestHelper.nodeUri( theStartNode.getId() ) );
Map<String, Object> jsonMap = JsonHelper.jsonToMap( response.getEntity() );
assertNotNull( jsonMap.containsKey( PAGED_TRAVERSE_LINK_REL ) );
assertThat( String.valueOf( jsonMap.get( PAGED_TRAVERSE_LINK_REL ) ),
containsString( "/db/data/node/" + String.valueOf( theStartNode.getId() )
+ "/paged/traverse/{returnType}{?pageSize,leaseTime}" ) );
}
/**
* Creating a paged traverser. Paged traversers are created by ++POST++-ing a
* traversal description to the link identified by the +paged_traverser+ key
* in a node representation. When creating a paged traverser, the same
* options apply as for a regular traverser, meaning that +node+, +path+,
* or +fullpath+, can be targeted.
*/
@Documented
@Test
public void shouldPostATraverserWithDefaultOptionsAndReceiveTheFirstPageOfResults() throws Exception
{
theStartNode = createLinkedList( SHORT_LIST_LENGTH, server.getDatabase() );
ResponseEntity entity = gen.get()
.expectedType( MediaType.valueOf( "application/json; charset=UTF-8" ) )
.expectedHeader( "Location" )
.expectedStatus( 201 )
.payload( traverserDescription() )
.payloadType( MediaType.APPLICATION_JSON_TYPE )
.post( functionalTestHelper.nodeUri( theStartNode.getId() ) + "/paged/traverse/node" );
assertEquals( 201, entity.response()
.getStatus() );
assertThat( entity.response()
.getLocation()
.toString(), containsString( "/db/data/node/" + theStartNode.getId() + "/paged/traverse/node/" ) );
assertEquals( "application/json; charset=UTF-8", entity.response()
.getType()
.toString() );
}
/**
* Paging through the results of a paged traverser. Paged traversers hold
* state on the server, and allow clients to page through the results of a
* traversal. To progress to the next page of traversal results, the client
* issues a HTTP GET request on the paged traversal URI which causes the
* traversal to fill the next page (or partially fill it if insufficient
* results are available).
*
* Note that if a traverser expires through inactivity it will cause a 404
* response on the next +GET+ request. Traversers' leases are renewed on
* every successful access for the same amount of time as originally
* specified.
*
* When the paged traverser reaches the end of its results, the client can
* expect a 404 response as the traverser is disposed by the server.
*/
@Documented
@Test
public void shouldBeAbleToTraverseAllThePagesWithDefaultPageSize()
{
theStartNode = createLinkedList( LONG_LIST_LENGTH, server.getDatabase() );
URI traverserLocation = createPagedTraverser().getLocation();
int enoughPagesToExpireTheTraverser = 3;
for ( int i = 0; i < enoughPagesToExpireTheTraverser; i++ )
{
gen.get()
.expectedType( MediaType.APPLICATION_JSON_TYPE )
.expectedStatus( 200 )
.payload( traverserDescription() )
.get( traverserLocation.toString() );
}
JaxRsResponse response = new RestRequest( traverserLocation ).get();
assertEquals( 404, response.getStatus() );
}
@Test
public void shouldExpireTheTraverserAfterDefaultTimeoutAndGetA404Response()
{
theStartNode = createLinkedList( SHORT_LIST_LENGTH, server.getDatabase() );
JaxRsResponse postResponse = createPagedTraverser();
assertEquals( 201, postResponse.getStatus() );
final int TEN_MINUTES = 10;
clock.forward( TEN_MINUTES, TimeUnit.MINUTES );
JaxRsResponse getResponse = new RestRequest( postResponse.getLocation() ).get();
assertEquals( 404, getResponse.getStatus() );
}
/**
* Paged traverser page size. The default page size is 50 items, but
* depending on the application larger or smaller pages sizes might be
* appropriate. This can be set by adding a +pageSize+ query parameter.
*/
@Documented
@Test
public void shouldBeAbleToTraverseAllThePagesWithNonDefaultPageSize()
{
theStartNode = createLinkedList( SHORT_LIST_LENGTH, server.getDatabase() );
URI traverserLocation = createPagedTraverserWithPageSize( 1 ).getLocation();
int enoughPagesToExpireTheTraverser = 12;
for ( int i = 0; i < enoughPagesToExpireTheTraverser; i++ )
{
JaxRsResponse response = new RestRequest( traverserLocation ).get();
assertEquals( 200, response.getStatus() );
}
JaxRsResponse response = new RestRequest( traverserLocation ).get();
assertEquals( 404, response.getStatus() );
}
/**
* Paged traverser timeout. The default timeout for a paged traverser is 60
* seconds, but depending on the application larger or smaller timeouts
* might be appropriate. This can be set by adding a +leaseTime+ query
* parameter with the number of seconds the paged traverser should last.
*/
@Documented
@Test
public void shouldExpireTraverserWithNonDefaultTimeout()
{
theStartNode = createLinkedList( SHORT_LIST_LENGTH, server.getDatabase() );
URI traverserLocation = createPagedTraverserWithTimeoutInMinutes( 10 ).getLocation();
clock.forward( 11, TimeUnit.MINUTES );
JaxRsResponse response = new RestRequest( traverserLocation ).get();
assertEquals( 404, response.getStatus() );
}
@Test
public void shouldTraverseAllPagesWithANonDefaultTimeoutAndNonDefaultPageSize()
{
theStartNode = createLinkedList( SHORT_LIST_LENGTH, server.getDatabase() );
URI traverserLocation = createPagedTraverserWithTimeoutInMinutesAndPageSize( 10, 2 ).getLocation();
int enoughPagesToExpireTheTraverser = 6;
for ( int i = 0; i < enoughPagesToExpireTheTraverser; i++ )
{
JaxRsResponse response = new RestRequest( traverserLocation ).get();
assertEquals( 200, response.getStatus() );
}
JaxRsResponse response = new RestRequest( traverserLocation ).get();
assertEquals( 404, response.getStatus() );
}
@Test
public void shouldRespondWith400OnNegativeLeaseTime()
{
theStartNode = createLinkedList( SHORT_LIST_LENGTH, server.getDatabase() );
int negativeLeaseTime = -9;
JaxRsResponse response = RestRequest.req().post(
functionalTestHelper.nodeUri( theStartNode.getId() ) + "/paged/traverse/node?leaseTime=" +
String.valueOf( negativeLeaseTime ), traverserDescription() );
assertEquals( 400, response.getStatus() );
}
@Test
public void shouldRespondWith400OnNegativePageSize()
{
theStartNode = createLinkedList( SHORT_LIST_LENGTH, server.getDatabase() );
int negativePageSize = -99;
JaxRsResponse response = RestRequest.req().post(
functionalTestHelper.nodeUri( theStartNode.getId() ) + "/paged/traverse/node?pageSize=" +
String.valueOf( negativePageSize ), traverserDescription() );
assertEquals( 400, response.getStatus() );
}
@Test
public void shouldRespondWith400OnScriptErrors()
{
GlobalJavascriptInitializer.initialize( GlobalJavascriptInitializer.Mode.SANDBOXED );
theStartNode = createLinkedList( 1, server.getDatabase() );
JaxRsResponse response = RestRequest.req().post(
functionalTestHelper.nodeUri( theStartNode.getId() ) + "/paged/traverse/node?pageSize=50",
"{"
+ "\"prune_evaluator\":{\"language\":\"builtin\",\"name\":\"none\"},"
+ "\"return_filter\":{\"language\":\"javascript\",\"body\":\"position.getClass()" +
".getClassLoader();\"},"
+ "\"order\":\"depth_first\","
+ "\"relationships\":{\"type\":\"NEXT\",\"direction\":\"out\"}"
+ "}" );
assertEquals( 400, response.getStatus() );
}
@Test
public void shouldRespondWith200OnFirstDeletionOfTraversalAnd404Afterwards()
{
theStartNode = createLinkedList( SHORT_LIST_LENGTH, server.getDatabase() );
JaxRsResponse response = createPagedTraverser();
final RestRequest request = RestRequest.req();
JaxRsResponse deleteResponse = request.delete( response.getLocation() );
assertEquals( 200, deleteResponse.getStatus() );
deleteResponse = request.delete( response.getLocation() );
assertEquals( 404, deleteResponse.getStatus() );
}
@Test
public void shouldAcceptJsonAndStreamingFlagAndProduceStreamedJson()
{
// given
theStartNode = createLinkedList( SHORT_LIST_LENGTH, server.getDatabase() );
// when
JaxRsResponse pagedTraverserResponse = createStreamingPagedTraverserWithTimeoutInMinutesAndPageSize( 60, 1 );
System.out.println( pagedTraverserResponse.getHeaders().getFirst( "Content-Type" ) );
// then
assertNotNull( pagedTraverserResponse.getHeaders().getFirst( "Content-Type" ) );
assertThat( pagedTraverserResponse.getHeaders().getFirst( "Content-Type" ),
containsString( "application/json; charset=UTF-8; stream=true" ) );
}
private JaxRsResponse createStreamingPagedTraverserWithTimeoutInMinutesAndPageSize( int leaseTimeInSeconds,
int pageSize )
{
String description = traverserDescription();
return RestRequest.req().header( "X-Stream", "true" ).post(
functionalTestHelper.nodeUri( theStartNode.getId() ) + "/paged/traverse/node?leaseTime="
+ leaseTimeInSeconds + "&pageSize=" + pageSize, description );
}
@Test
public void should201WithAcceptJsonHeader()
{
// given
theStartNode = createLinkedList( SHORT_LIST_LENGTH, server.getDatabase() );
String uri = functionalTestHelper.nodeUri( theStartNode.getId() ) + "/paged/traverse/node";
// when
JaxRsResponse response = RestRequest.req().accept( MediaType.APPLICATION_JSON_TYPE ).post( uri,
traverserDescription() );
// then
assertEquals( 201, response.getStatus() );
assertNotNull( response.getHeaders().getFirst( "Content-Type" ) );
assertThat( response.getType().toString(), containsString( MediaType.APPLICATION_JSON ) );
}
@Test
public void should201WithAcceptHtmlHeader()
{
// given
theStartNode = createLinkedList( SHORT_LIST_LENGTH, server.getDatabase() );
String uri = functionalTestHelper.nodeUri( theStartNode.getId() ) + "/paged/traverse/node";
// when
JaxRsResponse response = RestRequest.req().accept( MediaType.TEXT_HTML_TYPE ).post( uri,
traverserDescription() );
// then
assertEquals( 201, response.getStatus() );
assertNotNull( response.getHeaders().getFirst( "Content-Type" ) );
assertThat( response.getType().toString(), containsString( MediaType.TEXT_HTML ) );
}
@Test
public void shouldHaveTransportEncodingChunkedOnResponseHeader()
{
// given
theStartNode = createLinkedList( SHORT_LIST_LENGTH, server.getDatabase() );
// when
JaxRsResponse response = createStreamingPagedTraverserWithTimeoutInMinutesAndPageSize( 60, 1 );
// then
assertEquals( 201, response.getStatus() );
assertEquals( "application/json; charset=UTF-8; stream=true", response.getHeaders().getFirst( "Content-Type"
) );
assertThat( response.getHeaders().getFirst( "Transfer-Encoding" ), containsString( "chunked" ) );
}
private JaxRsResponse createPagedTraverserWithTimeoutInMinutesAndPageSize( final int leaseTimeInSeconds,
final int pageSize )
{
String description = traverserDescription();
return RestRequest.req().post(
functionalTestHelper.nodeUri( theStartNode.getId() ) + "/paged/traverse/node?leaseTime="
+ leaseTimeInSeconds + "&pageSize=" + pageSize, description );
}
private JaxRsResponse createPagedTraverserWithTimeoutInMinutes( final int leaseTime )
{
ResponseEntity responseEntity = gen.get()
.expectedType( MediaType.APPLICATION_JSON_TYPE )
.expectedStatus( 201 )
.payload( traverserDescription() )
.post( functionalTestHelper.nodeUri( theStartNode.getId() ) + "/paged/traverse/node?leaseTime="
+ String.valueOf( leaseTime ) );
return responseEntity.response();
}
private JaxRsResponse createPagedTraverserWithPageSize( final int pageSize )
{
ResponseEntity responseEntity = gen.get()
.expectedType( MediaType.APPLICATION_JSON_TYPE )
.expectedStatus( 201 )
.payload( traverserDescription() )
.post( functionalTestHelper.nodeUri( theStartNode.getId() ) + "/paged/traverse/node?pageSize="
+ String.valueOf( pageSize ) );
return responseEntity.response();
}
private JaxRsResponse createPagedTraverser()
{
final String uri = functionalTestHelper.nodeUri( theStartNode.getId() ) + "/paged/traverse/node";
return RestRequest.req().post( uri, traverserDescription() );
}
private String traverserDescription()
{
String description = "{"
+ "\"prune_evaluator\":{\"language\":\"builtin\",\"name\":\"none\"},"
+ "\"return_filter\":{\"language\":\"javascript\",\"body\":\"position.endNode().getProperty('name')" +
".contains('1');\"},"
+ "\"order\":\"depth_first\","
+ "\"relationships\":{\"type\":\"NEXT\",\"direction\":\"out\"}"
+ "}";
return description;
}
private Node createLinkedList( final int listLength, final Database db )
{
Node startNode = null;
try ( Transaction tx = db.getGraph().beginTx() )
{
Node previous = null;
for ( int i = 0; i < listLength; i++ )
{
Node current = db.getGraph().createNode();
current.setProperty( "name", String.valueOf( i ) );
if ( previous != null )
{
previous.createRelationshipTo( current, DynamicRelationshipType.withName( "NEXT" ) );
}
else
{
startNode = current;
}
previous = current;
}
tx.success();
return startNode;
}
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_paging_PagedTraverserDocIT.java
|
2,813
|
public class DiscoveryRepresentation extends MappingRepresentation
{
private static final String DATA_URI_KEY = "data";
private static final String MANAGEMENT_URI_KEY = "management";
private static final String DISCOVERY_REPRESENTATION_TYPE = "discovery";
private final String managementUri;
private final String dataUri;
public DiscoveryRepresentation( String managementUri, String dataUri )
{
super( DISCOVERY_REPRESENTATION_TYPE );
this.managementUri = managementUri;
this.dataUri = dataUri;
}
@Override
protected void serialize( MappingSerializer serializer )
{
serializer.putUri( MANAGEMENT_URI_KEY, managementUri );
serializer.putUri( DATA_URI_KEY, dataUri );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_DiscoveryRepresentation.java
|
2,814
|
public class DefaultFormat extends RepresentationFormat
{
private final RepresentationFormat inner;
private final Collection<MediaType> supported;
private final MediaType[] requested;
public DefaultFormat( RepresentationFormat inner, Collection<MediaType> supported, MediaType... requested )
{
super( MediaType.APPLICATION_JSON_TYPE );
this.inner = inner;
this.supported = supported;
this.requested = requested;
}
@Override
protected String serializeValue( String type, Object value )
{
return inner.serializeValue( type, value );
}
@Override
protected ListWriter serializeList( String type )
{
return inner.serializeList( type );
}
@Override
protected MappingWriter serializeMapping( String type )
{
return inner.serializeMapping( type );
}
@Override
protected String complete( ListWriter serializer )
{
return inner.complete( serializer );
}
@Override
protected String complete( MappingWriter serializer )
{
return inner.complete( serializer );
}
@Override
public Object readValue( String input )
{
try
{
return inner.readValue( input );
}
catch ( BadInputException e )
{
throw newMediaTypeNotSupportedException();
}
}
private MediaTypeNotSupportedException newMediaTypeNotSupportedException()
{
return new MediaTypeNotSupportedException( Response.Status.UNSUPPORTED_MEDIA_TYPE, supported, requested );
}
@Override
public Map<String, Object> readMap( String input, String... requiredKeys ) throws BadInputException
{
Map<String, Object> result;
try
{
result = inner.readMap( input );
}
catch ( BadInputException e )
{
throw newMediaTypeNotSupportedException();
}
return validateKeys( result, requiredKeys );
}
@Override
public List<Object> readList( String input ) throws BadInputException
{
try
{
return inner.readList( input );
}
catch ( BadInputException e )
{
throw newMediaTypeNotSupportedException();
}
}
@Override
public URI readUri( String input ) throws BadInputException
{
try
{
return inner.readUri( input );
}
catch ( BadInputException e )
{
throw newMediaTypeNotSupportedException();
}
}
public static <T> Map<String, T> validateKeys( Map<String, T> map, String... requiredKeys ) throws BadInputException
{
Set<String> missing = null;
for ( String key : requiredKeys )
{
if ( !map.containsKey( key ) ) ( missing == null ? ( missing = new HashSet<String>() ) : missing ).add( key );
}
if ( missing != null )
{
if ( missing.size() == 1 )
{
throw new BadInputException( "Missing required key: \"" + missing.iterator().next() + "\"" );
}
else
{
throw new BadInputException( "Missing required keys: " + missing );
}
}
return map;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_DefaultFormat.java
|
2,815
|
public class DatabaseRepresentation extends MappingRepresentation implements ExtensibleRepresentation
{
public DatabaseRepresentation()
{
super( RepresentationType.GRAPHDB );
}
@Override
public String getIdentity()
{
// This is in fact correct - there is only one graphdb - hence no id
return null;
}
@Override
protected void serialize( MappingSerializer serializer )
{
serializer.putUri( "node", PATH_NODES );
serializer.putUri( "node_index", PATH_NODE_INDEX );
serializer.putUri( "relationship_index", PATH_RELATIONSHIP_INDEX );
serializer.putUri( "extensions_info", PATH_EXTENSIONS );
serializer.putUri( "relationship_types", PATH_RELATIONSHIP_TYPES );
serializer.putUri( "batch", PATH_BATCH );
serializer.putUri( "cypher", PATH_CYPHER );
serializer.putUri( "indexes", PATH_SCHEMA_INDEX );
serializer.putUri( "constraints", PATH_SCHEMA_CONSTRAINT );
serializer.putUri( "transaction", PATH_TRANSACTION );
serializer.putUri( "node_labels", PATH_LABELS );
serializer.putString( "neo4j_version", Version.getKernel().getReleaseVersion() );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_DatabaseRepresentation.java
|
2,816
|
public class CypherResultRepresentationTest
{
private static final ResourceIterator EMPTY_ITERATOR = emptyIterator();
@Test
@SuppressWarnings("unchecked")
public void shouldSerializeProfilingResult() throws Exception
{
// Given
String name = "Kalle";
PlanDescription plan = getMockDescription( name );
PlanDescription childPlan = getMockDescription( "child" );
when( plan.getChildren() ).thenReturn( asList( childPlan ) );
when( plan.hasProfilerStatistics() ).thenReturn( true );
ProfilerStatistics stats = mock( ProfilerStatistics.class );
when( stats.getDbHits() ).thenReturn( 13l );
when( stats.getRows() ).thenReturn( 25l );
when( plan.getProfilerStatistics() ).thenReturn( stats );
ExecutionResult result = mock( ExecutionResult.class );
when( result.iterator() ).thenReturn( EMPTY_ITERATOR );
when( result.columns() ).thenReturn( new ArrayList<String>() );
when( result.executionPlanDescription() ).thenReturn( plan );
// When
Map<String, Object> serialized = serializeToStringThenParseAsToMap( new CypherResultRepresentation( result,
/*includeStats=*/false, true ) );
// Then
Map<String, Object> serializedPlan = (Map<String, Object>) serialized.get( "plan" );
assertThat( (String) serializedPlan.get( "name" ), equalTo( name ) );
assertThat( (Integer) serializedPlan.get( "rows" ), is( 25 ) );
assertThat( (Integer) serializedPlan.get( "dbHits" ), is( 13 ) );
List<Map<String, Object>> children = (List<Map<String, Object>>) serializedPlan.get( "children" );
assertThat( children.size(), is( 1 ) );
Map<String, Object> args = (Map<String, Object>) serializedPlan.get( "args" );
assertThat( (String) args.get( "argumentKey" ), is( "argumentValue" ) );
}
@Test
@SuppressWarnings("unchecked")
public void shouldNotIncludePlanUnlessAskedFor() throws Exception
{
// Given
ExecutionResult result = mock( ExecutionResult.class );
when( result.iterator() ).thenReturn( EMPTY_ITERATOR );
when( result.columns() ).thenReturn( new ArrayList<String>() );
// When
Map<String, Object> serialized = serializeToStringThenParseAsToMap( new CypherResultRepresentation( result,
/*includeStats=*/false, false ) );
// Then
assertFalse( "Didn't expect to see a plan here", serialized.containsKey( "plan" ) );
}
@Rule
public DatabaseRule database = new ImpermanentDatabaseRule();
@Test
public void shouldFormatMapsProperly() throws Exception
{
ExecutionEngine executionEngine = new ExecutionEngine( database.getGraphDatabaseService() );
ExecutionResult result = executionEngine.execute( "RETURN {one:{two:['wait for it...', {three: 'GO!'}]}}" );
CypherResultRepresentation representation = new CypherResultRepresentation( result, false, false );
// When
Map<String, Object> serialized = serializeToStringThenParseAsToMap( representation );
// Then
Map one = (Map) ((Map) ((List) ((List) serialized.get( "data" )).get( 0 )).get( 0 )).get( "one" );
List two = (List) one.get( "two" );
assertThat( (String) two.get( 0 ), is( "wait for it..." ) );
Map foo = (Map) two.get( 1 );
assertThat( (String) foo.get( "three" ), is( "GO!" ) );
}
@Test
public void shouldRenderNestedEntities() throws Exception
{
try ( Transaction ignored = database.getGraphDatabaseService().beginTx() )
{
ExecutionEngine executionEngine = new ExecutionEngine( database.getGraphDatabaseService() );
executionEngine.execute( "CREATE (n {name: 'Sally'}), (m {age: 42}), n-[r:FOO {drunk: false}]->m" );
ExecutionResult result = executionEngine.execute( "MATCH p=n-[r]->m RETURN n, r, p, {node: n, edge: r, " +
"path: p}" );
CypherResultRepresentation representation = new CypherResultRepresentation( result, false, false );
// When
Map<String, Object> serialized = serializeToStringThenParseAsToMap( representation );
// Then
Object firstRow = ((List) serialized.get( "data" )).get( 0 );
Map nested = (Map) ((List) firstRow).get( 3 );
assertThat( nested.get( "node" ), is( equalTo( ((List) firstRow).get( 0 ) ) ) );
assertThat( nested.get( "edge" ), is( equalTo( ((List) firstRow).get( 1 ) ) ) );
assertThat( nested.get( "path" ), is( equalTo( ((List) firstRow).get( 2 ) ) ) );
}
}
private static ResourceIterator<Map<String, Object>> emptyIterator()
{
@SuppressWarnings("unchecked")
ResourceIterator<Map<String, Object>> iterator = mock( ResourceIterator.class );
when( iterator.hasNext() ).thenReturn( false );
return iterator;
}
private PlanDescription getMockDescription( String name )
{
PlanDescription plan = mock( PlanDescription.class );
when( plan.getName() ).thenReturn( name );
when( plan.getArguments() ).thenReturn( MapUtil.map( "argumentKey", "argumentValue" ) );
return plan;
}
private Map<String, Object> serializeToStringThenParseAsToMap( CypherResultRepresentation repr ) throws Exception
{
OutputFormat format = new OutputFormat( new JsonFormat(), new URI( "http://localhost/" ), null );
return jsonToMap( format.assemble( repr ) );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_repr_CypherResultRepresentationTest.java
|
2,817
|
return new Function<Object,PlanDescription>(){
@Override
public PlanDescription apply( Object from )
{
return result.executionPlanDescription();
}
};
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_CypherResultRepresentation.java
|
2,818
|
return createPlanRepresentation( new Function<Object, PlanDescription>(){
@Override
public PlanDescription apply( Object from )
{
return childPlan;
}
});
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_CypherResultRepresentation.java
|
2,819
|
new IterableWrapper<Representation, PlanDescription>(planDescription.getChildren()) {
@Override
protected Representation underlyingObjectToObject( final PlanDescription childPlan )
{
return createPlanRepresentation( new Function<Object, PlanDescription>(){
@Override
public PlanDescription apply( Object from )
{
return childPlan;
}
});
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_CypherResultRepresentation.java
|
2,820
|
return new MappingRepresentation( "plan" ) {
@Override
protected void serialize( MappingSerializer mappingSerializer )
{
final PlanDescription planDescription = getPlan.apply( null );
mappingSerializer.putString( "name", planDescription.getName() );
MappingRepresentation argsRepresentation = getMapRepresentation( (Map) planDescription.getArguments() );
mappingSerializer.putMapping( "args", argsRepresentation );
if ( planDescription.hasProfilerStatistics() )
{
ProfilerStatistics stats = planDescription.getProfilerStatistics();
mappingSerializer.putNumber( "rows", stats.getRows() );
mappingSerializer.putNumber( "dbHits", stats.getDbHits() );
}
mappingSerializer.putList( "children",
new ListRepresentation( "children",
new IterableWrapper<Representation, PlanDescription>(planDescription.getChildren()) {
@Override
protected Representation underlyingObjectToObject( final PlanDescription childPlan )
{
return createPlanRepresentation( new Function<Object, PlanDescription>(){
@Override
public PlanDescription apply( Object from )
{
return childPlan;
}
});
}
}
)
);
}
};
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_CypherResultRepresentation.java
|
2,821
|
new IterableWrapper<Representation,String>(columns) {
@Override
protected Representation underlyingObjectToObject(String column) {
return getRepresentation( row.get( column ) );
}
});
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_CypherResultRepresentation.java
|
2,822
|
return new ListRepresentation( "data", new IterableWrapper<Representation,Map<String,Object>>(inner) {
@Override
protected Representation underlyingObjectToObject(final Map<String, Object> row) {
return new ListRepresentation("row",
new IterableWrapper<Representation,String>(columns) {
@Override
protected Representation underlyingObjectToObject(String column) {
return getRepresentation( row.get( column ) );
}
});
}
});
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_CypherResultRepresentation.java
|
2,823
|
{
@Override
protected void serialize( MappingSerializer serializer )
{
serializer.putBoolean( "contains_updates", stats.containsUpdates() );
serializer.putNumber( "nodes_created", stats.getNodesCreated() );
serializer.putNumber( "nodes_deleted", stats.getDeletedNodes() );
serializer.putNumber( "properties_set", stats.getPropertiesSet() );
serializer.putNumber( "relationships_created", stats.getRelationshipsCreated() );
serializer.putNumber( "relationship_deleted", stats.getDeletedRelationships() );
serializer.putNumber( "labels_added", stats.getLabelsAdded() );
serializer.putNumber( "labels_removed", stats.getLabelsRemoved() );
serializer.putNumber( "indexes_added", stats.getIndexesAdded() );
serializer.putNumber( "indexes_removed", stats.getIndexesRemoved() );
serializer.putNumber( "constraints_added", stats.getConstraintsAdded() );
serializer.putNumber( "constraints_removed", stats.getConstraintsRemoved() );
}
};
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_CypherResultRepresentation.java
|
2,824
|
public class CypherResultRepresentation extends MappingRepresentation
{
private static final RepresentationDispatcher REPRESENTATION_DISPATCHER = new CypherRepresentationDispatcher();
private final ListRepresentation resultRepresentation;
private final ListRepresentation columns;
private final MappingRepresentation statsRepresentation;
private final MappingRepresentation plan;
public CypherResultRepresentation( final ExecutionResult result, boolean includeStats, boolean includePlan )
{
super( RepresentationType.STRING );
resultRepresentation = createResultRepresentation( result );
columns = ListRepresentation.string( result.columns() );
statsRepresentation = includeStats ? createStatsRepresentation( result.getQueryStatistics() ) : null;
plan = includePlan ? createPlanRepresentation( planProvider( result ) ) : null;
}
private MappingRepresentation createStatsRepresentation( final QueryStatistics stats )
{
return new MappingRepresentation( "stats" )
{
@Override
protected void serialize( MappingSerializer serializer )
{
serializer.putBoolean( "contains_updates", stats.containsUpdates() );
serializer.putNumber( "nodes_created", stats.getNodesCreated() );
serializer.putNumber( "nodes_deleted", stats.getDeletedNodes() );
serializer.putNumber( "properties_set", stats.getPropertiesSet() );
serializer.putNumber( "relationships_created", stats.getRelationshipsCreated() );
serializer.putNumber( "relationship_deleted", stats.getDeletedRelationships() );
serializer.putNumber( "labels_added", stats.getLabelsAdded() );
serializer.putNumber( "labels_removed", stats.getLabelsRemoved() );
serializer.putNumber( "indexes_added", stats.getIndexesAdded() );
serializer.putNumber( "indexes_removed", stats.getIndexesRemoved() );
serializer.putNumber( "constraints_added", stats.getConstraintsAdded() );
serializer.putNumber( "constraints_removed", stats.getConstraintsRemoved() );
}
};
}
@Override
protected void serialize( MappingSerializer serializer )
{
serializer.putList( "columns", columns );
serializer.putList( "data", resultRepresentation );
if (statsRepresentation != null)
serializer.putMapping( "stats", statsRepresentation );
if (plan != null)
serializer.putMapping( "plan", plan );
}
private ListRepresentation createResultRepresentation(ExecutionResult executionResult) {
final List<String> columns = executionResult.columns();
final Iterable<Map<String, Object>> inner = new RepresentationExceptionHandlingIterable<Map<String,Object>>(executionResult);
return new ListRepresentation( "data", new IterableWrapper<Representation,Map<String,Object>>(inner) {
@Override
protected Representation underlyingObjectToObject(final Map<String, Object> row) {
return new ListRepresentation("row",
new IterableWrapper<Representation,String>(columns) {
@Override
protected Representation underlyingObjectToObject(String column) {
return getRepresentation( row.get( column ) );
}
});
}
});
}
/*
* This takes a function that resolves to a {@link PlanDescription}, and it does so for two reasons:
* - The plan description needs to be fetched *after* the result is streamed to the user
* - This method is recursive, so it's not enough to just pass in the executionplan to the root call of it
* subsequent inner calls could not re-use that execution plan (that would just lead to an infinite loop)
*/
private MappingRepresentation createPlanRepresentation( final Function<Object, PlanDescription> getPlan )
{
return new MappingRepresentation( "plan" ) {
@Override
protected void serialize( MappingSerializer mappingSerializer )
{
final PlanDescription planDescription = getPlan.apply( null );
mappingSerializer.putString( "name", planDescription.getName() );
MappingRepresentation argsRepresentation = getMapRepresentation( (Map) planDescription.getArguments() );
mappingSerializer.putMapping( "args", argsRepresentation );
if ( planDescription.hasProfilerStatistics() )
{
ProfilerStatistics stats = planDescription.getProfilerStatistics();
mappingSerializer.putNumber( "rows", stats.getRows() );
mappingSerializer.putNumber( "dbHits", stats.getDbHits() );
}
mappingSerializer.putList( "children",
new ListRepresentation( "children",
new IterableWrapper<Representation, PlanDescription>(planDescription.getChildren()) {
@Override
protected Representation underlyingObjectToObject( final PlanDescription childPlan )
{
return createPlanRepresentation( new Function<Object, PlanDescription>(){
@Override
public PlanDescription apply( Object from )
{
return childPlan;
}
});
}
}
)
);
}
};
}
private Representation getRepresentation( Object r )
{
if( r == null )
{
return ValueRepresentation.string( null );
}
if ( r instanceof Path )
{
return new PathRepresentation<Path>((Path) r );
}
if(r instanceof Iterable)
{
return handleIterable( (Iterable) r );
}
if ( r instanceof Node)
{
return new NodeRepresentation( (Node) r );
}
if ( r instanceof Relationship)
{
return new RelationshipRepresentation( (Relationship) r );
}
return REPRESENTATION_DISPATCHER.dispatch( r, "" );
}
private Representation handleIterable( Iterable data ) {
final List<Representation> results = new ArrayList<Representation>();
for ( final Object value : data )
{
Representation rep = getRepresentation(value);
results.add(rep);
}
RepresentationType representationType = getType(results);
return new ListRepresentation( representationType, results );
}
private RepresentationType getType( List<Representation> representations )
{
if ( representations == null || representations.isEmpty() )
return RepresentationType.STRING;
return representations.get( 0 ).getRepresentationType();
}
private Function<Object, PlanDescription> planProvider( final ExecutionResult result )
{
return new Function<Object,PlanDescription>(){
@Override
public PlanDescription apply( Object from )
{
return result.executionPlanDescription();
}
};
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_CypherResultRepresentation.java
|
2,825
|
public class CypherRepresentationDispatcher extends RepresentationDispatcher
{
@Override
protected Representation dispatchOtherProperty( Object property, String param )
{
if ( property instanceof Map )
{
return new MapRepresentation( (Map) property );
}
else
{
return super.dispatchOtherProperty( property, param );
}
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_CypherRepresentationDispatcher.java
|
2,826
|
{
@Override
public Representation apply( String propertyKey )
{
return ValueRepresentation.string( propertyKey );
}
};
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_ConstraintDefinitionRepresentation.java
|
2,827
|
public class ConstraintDefinitionRepresentation extends MappingRepresentation
{
protected final ConstraintDefinition constraintDefinition;
public ConstraintDefinitionRepresentation( ConstraintDefinition constraintDefinition )
{
super( CONSTRAINT_DEFINITION );
this.constraintDefinition = constraintDefinition;
}
@Override
protected void serialize( MappingSerializer serializer )
{
serializer.putString( "label", constraintDefinition.getLabel().name() );
ConstraintType type = constraintDefinition.getConstraintType();
serializer.putString( "type", type.name() );
serialize( constraintDefinition, serializer );
}
protected void serialize( ConstraintDefinition constraintDefinition, MappingSerializer serializer )
{
Function<String, Representation> converter = new Function<String, Representation>()
{
@Override
public Representation apply( String propertyKey )
{
return ValueRepresentation.string( propertyKey );
}
};
Iterable<Representation> propertyKeyRepresentations = map( converter, constraintDefinition.getPropertyKeys() );
serializer.putList( "property_keys",
new ListRepresentation( RepresentationType.STRING, propertyKeyRepresentations ) );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_ConstraintDefinitionRepresentation.java
|
2,828
|
public class BadInputException extends Exception
{
public BadInputException( Throwable cause )
{
super( cause.getMessage(), cause );
}
public BadInputException( String message )
{
super( message );
}
public BadInputException( String message, Throwable cause )
{
super( message, cause );
}
}
| false
|
community_server-api_src_main_java_org_neo4j_server_rest_repr_BadInputException.java
|
2,829
|
public class PagedTraverserTest
{
private static final int LIST_LENGTH = 100;
private Database database;
private Node startNode;
@Before
public void clearDb() throws Throwable
{
database = new EphemeralDatabase( Configurator.EMPTY );
database.start();
createLinkedList( LIST_LENGTH, database );
}
@After
public void shutdownDatabase() throws Throwable
{
database.getGraph().shutdown();
}
private void createLinkedList( int listLength, Database db )
{
try ( Transaction tx = db.getGraph().beginTx() )
{
Node previous = null;
for ( int i = 0; i < listLength; i++ )
{
Node current = db.getGraph().createNode();
if ( previous != null )
{
previous.createRelationshipTo( current, DynamicRelationshipType.withName( "NEXT" ) );
}
else
{
startNode = current;
}
previous = current;
}
tx.success();
}
}
@Test
public void shouldPageThroughResultsForWhollyDivisiblePageSize()
{
Traverser myTraverser = simpleListTraverser();
PagedTraverser traversalPager = new PagedTraverser( myTraverser, LIST_LENGTH / 10 );
int iterations = iterateThroughPagedTraverser( traversalPager );
assertEquals( 10, iterations );
assertNull( traversalPager.next() );
}
@SuppressWarnings( "unused" )
private int iterateThroughPagedTraverser( PagedTraverser traversalPager )
{
try ( Transaction transaction = database.getGraph().beginTx() )
{
int count = 0;
for ( List<Path> paths : traversalPager )
{
count++;
}
transaction.success();
return count;
}
}
@Test
public void shouldPageThroughResultsForNonWhollyDivisiblePageSize()
{
int awkwardPageSize = 7;
Traverser myTraverser = simpleListTraverser();
PagedTraverser traversalPager = new PagedTraverser( myTraverser, awkwardPageSize );
int iterations = iterateThroughPagedTraverser( traversalPager );
assertEquals( 15, iterations );
assertNull( traversalPager.next() );
}
private Traverser simpleListTraverser()
{
return Traversal.description()
.expand( Traversal.expanderForTypes( DynamicRelationshipType.withName( "NEXT" ), Direction.OUTGOING ) )
.depthFirst()
.uniqueness( Uniqueness.NODE_GLOBAL )
.traverse( startNode );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_paging_PagedTraverserTest.java
|
2,830
|
{
@Override
public Void call() throws Exception
{
server.stop();
return null;
}
} );
| false
|
community_server_src_test_java_org_neo4j_server_rest_paging_PagedTraverserDocIT.java
|
2,831
|
{
@Override
public Void call() throws Exception
{
server.start();
return null;
}
} );
| false
|
community_server_src_test_java_org_neo4j_server_rest_paging_PagedTraverserDocIT.java
|
2,832
|
public class PropertySettingStrategy
{
private final GraphDatabaseAPI db;
public PropertySettingStrategy( GraphDatabaseAPI db )
{
this.db = db;
}
/**
* Set all properties on an entity, deleting any properties that existed on the entity but not in the
* provided map.
*
* @param entity
* @param properties
*/
public void setAllProperties( PropertyContainer entity, Map<String, Object> properties ) throws PropertyValueException
{
Map<String, Object> propsToSet = properties == null ?
new HashMap<String, Object>() :
properties;
try ( Transaction tx = db.beginTx() )
{
setProperties( entity, properties );
ensureHasOnlyTheseProperties( entity, propsToSet.keySet() );
tx.success();
}
}
private void ensureHasOnlyTheseProperties( PropertyContainer entity, Set<String> propertiesThatShouldExist )
{
for ( String entityPropertyKey : entity.getPropertyKeys() )
{
if( ! propertiesThatShouldExist.contains( entityPropertyKey ))
{
entity.removeProperty( entityPropertyKey );
}
}
}
public void setProperties( PropertyContainer entity, Map<String, Object> properties ) throws PropertyValueException
{
if ( properties != null )
{
try ( Transaction tx = db.beginTx() )
{
for ( Map.Entry<String, Object> property : properties.entrySet() )
{
setProperty( entity, property.getKey(), property.getValue() );
}
tx.success();
}
}
}
public void setProperty(PropertyContainer entity, String key, Object value) throws PropertyValueException
{
if ( value instanceof Collection )
{
if ( ((Collection<?>) value).size() == 0 )
{
// Special case: Trying to set an empty array property. We cannot determine the type
// of the collection now, so we fall back to checking if there already is a collection
// on the entity, and either leave it intact if it is empty, or set it to an empty collection
// of the same type as the original
Object currentValue = entity.getProperty( key, null );
if(currentValue != null &&
currentValue.getClass().isArray())
{
if ( Array.getLength( currentValue ) == 0 )
{
// Ok, leave it this way
return;
}
value = emptyArrayOfType(currentValue.getClass().getComponentType());
}
else
{
throw new PropertyValueException(
"Unable to set property '" + key + "' to an empty array, " +
"because, since there are no values of any type in it, " +
"and no pre-existing collection to infer type from, it is not possible " +
"to determine what type of array to store." );
}
}
else
{
// Non-empty collection
value = convertToNativeArray( (Collection<?>) value );
}
}
try ( Transaction tx = db.beginTx() )
{
entity.setProperty( key, value );
tx.success();
}
catch ( IllegalArgumentException e )
{
throw new PropertyValueException( key, value );
}
}
public Object convert( Object value ) throws PropertyValueException
{
if ( !(value instanceof Collection) )
{
return value;
}
if ( ((Collection<?>) value).size() == 0 )
{
throw new PropertyValueException(
"Unable to convert '" + value + "' to an empty array, " +
"because, since there are no values of any type in it, " +
"and no pre-existing collection to infer type from, it is not possible " +
"to determine what type of array to store." );
}
return convertToNativeArray( (Collection<?>) value );
}
private Object emptyArrayOfType( Class<?> cls ) throws PropertyValueException
{
return Array.newInstance( cls, 0);
}
public static Object convertToNativeArray( Collection<?> collection )
{
Object[] array = null;
Iterator<?> objects = collection.iterator();
for ( int i = 0; objects.hasNext(); i++ )
{
Object object = objects.next();
if ( array == null )
{
array = (Object[]) Array.newInstance( object.getClass(),
collection.size() );
}
array[i] = object;
}
return array;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_domain_PropertySettingStrategy.java
|
2,833
|
public class JsonHelper
{
static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
public static JsonNode jsonNode(String json) throws JsonParseException
{
try
{
return OBJECT_MAPPER.readTree( json );
}
catch ( IOException e )
{
throw new JsonParseException( e );
}
}
@SuppressWarnings( "unchecked" )
public static Map<String, Object> jsonToMap( String json ) throws JsonParseException
{
return (Map<String, Object>) readJson( json );
}
@SuppressWarnings( "unchecked" )
public static List<Map<String, Object>> jsonToList( String json ) throws JsonParseException
{
return (List<Map<String, Object>>) readJson( json );
}
public static Object readJson( String json ) throws JsonParseException
{
try
{
return OBJECT_MAPPER.readValue( json, Object.class );
}
catch ( IOException e )
{
throw new JsonParseException( e );
}
}
public static Object jsonToSingleValue( String json ) throws org.neo4j.server.rest.web.PropertyValueException
{
Object jsonObject = readJson( json );
return jsonObject instanceof Collection<?> ? jsonObject : assertSupportedPropertyValue( jsonObject );
}
private static Object assertSupportedPropertyValue( Object jsonObject ) throws PropertyValueException
{
if ( jsonObject == null )
{
throw new org.neo4j.server.rest.web.PropertyValueException( "null value not supported" );
}
if ( !(jsonObject instanceof String ||
jsonObject instanceof Number ||
jsonObject instanceof Boolean) )
{
throw new org.neo4j.server.rest.web.PropertyValueException(
"Unsupported value type " + jsonObject.getClass() + "."
+ " Supported value types are all java primitives (byte, char, short, int, "
+ "long, float, double) and String, as well as arrays of all those types" );
}
return jsonObject;
}
public static String createJsonFrom( Object data ) throws JsonBuildRuntimeException
{
try
{
StringWriter writer = new StringWriter();
JsonGenerator generator = OBJECT_MAPPER.getJsonFactory()
.createJsonGenerator( writer )
.useDefaultPrettyPrinter();
OBJECT_MAPPER.writeValue( generator, data );
writer.close();
return writer.getBuffer()
.toString();
}
catch ( IOException e )
{
throw new JsonBuildRuntimeException( e );
}
}
public static String prettyPrint( Object item ) throws IOException
{
return OBJECT_MAPPER.writer().withDefaultPrettyPrinter().writeValueAsString( item );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_domain_JsonHelper.java
|
2,834
|
RELATIONSHIP( Representation.RELATIONSHIP )
{
@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,835
|
public class TraverserDocIT extends AbstractRestFunctionalTestBase
{
@Test
public void shouldGet404WhenTraversingFromNonExistentNode()
{
gen().expectedStatus( Status.NOT_FOUND.getStatusCode() ).payload(
"{}" ).post( getDataUri() + "node/10000/traverse/node" ).entity();
}
@Test
@Graph( nodes = {@NODE(name="I")} )
public void shouldGet200WhenNoHitsFromTraversing()
{
assertSize( 0,gen().expectedStatus( 200 ).payload( "" ).post(
getTraverseUriNodes( getNode( "I" ) ) ).entity());
}
/**
* In order to return relationships,
* simply specify the return type as part of the URL.
*/
@Test
@Graph( {"I know you", "I own car"} )
public void return_relationships_from_a_traversal()
{
assertSize( 2, gen().expectedStatus( 200 ).payload( "{\"order\":\"breadth_first\",\"uniqueness\":\"none\",\"return_filter\":{\"language\":\"builtin\",\"name\":\"all\"}}" ).post(
getTraverseUriRelationships( getNode( "I" ) ) ).entity());
}
/**
* In order to return paths from a traversal,
* specify the +Path+ return type as part of the URL.
*/
@Test
@Graph( {"I know you", "I own car"} )
public void return_paths_from_a_traversal()
{
assertSize( 3, gen().expectedStatus( 200 ).payload( "{\"order\":\"breadth_first\",\"uniqueness\":\"none\",\"return_filter\":{\"language\":\"builtin\",\"name\":\"all\"}}" ).post(
getTraverseUriPaths( getNode( "I" ) ) ).entity());
}
private String getTraverseUriRelationships( Node node )
{
return getNodeUri( node) + "/traverse/relationship";
}
private String getTraverseUriPaths( Node node )
{
return getNodeUri( node) + "/traverse/path";
}
private String getTraverseUriNodes( Node node )
{
// TODO Auto-generated method stub
return getNodeUri( node) + "/traverse/node";
}
@Test
@Graph( "I know you" )
public void shouldGetSomeHitsWhenTraversingWithDefaultDescription()
throws PropertyValueException
{
String entity = gen().expectedStatus( Status.OK.getStatusCode() ).payload( "{}" ).post(
getTraverseUriNodes( getNode( "I" ) ) ).entity();
expectNodes( entity, getNode( "you" ));
}
private void expectNodes( String entity, Node... nodes )
throws PropertyValueException
{
Set<String> expected = new HashSet<>();
for ( Node node : nodes )
{
expected.add( getNodeUri( node ) );
}
Collection<?> items = (Collection<?>) JsonHelper.jsonToSingleValue( entity );
for ( Object item : items )
{
Map<?, ?> map = (Map<?, ?>) item;
String uri = (String) map.get( "self" );
assertTrue( uri + " not found", expected.remove( uri ) );
}
assertTrue( "Expected not empty:" + expected, expected.isEmpty() );
}
/**
* Traversal using a return filter.
*
* In this example, the +none+ prune evaluator is used and a return filter
* is supplied in order to return all names containing "t".
* The result is to be returned as nodes and the max depth is
* set to 3.
*/
@Documented
@Graph( {"Root knows Mattias", "Root knows Johan", "Johan knows Emil", "Emil knows Peter", "Emil knows Tobias", "Tobias loves Sara"} )
@Test
public void shouldGetExpectedHitsWhenTraversingWithDescription()
throws PropertyValueException
{
Node start = getNode( "Root" );
List<Map<String, Object>> rels = new ArrayList<>();
rels.add( map( "type", "knows", "direction", "all" ) );
rels.add( map( "type", "loves", "direction", "all" ) );
String description = createJsonFrom( map(
"order",
"breadth_first",
"uniqueness",
"node_global",
"prune_evaluator",
map( "language", "javascript", "body", "position.length() > 10" ),
"return_filter",
map( "language", "javascript", "body",
"position.endNode().getProperty('name').toLowerCase().contains('t')" ),
"relationships", rels, "max_depth", 3 ) );
String entity = gen().expectedStatus( 200 ).payload( description ).post(
getTraverseUriNodes( start ) ).entity();
expectNodes( entity, getNodes( "Root", "Mattias", "Peter", "Tobias" ) );
}
/**
* Traversal returning nodes below a certain depth.
*
* Here, all nodes at a traversal depth below 3 are returned.
*/
@Documented
@Graph( {"Root knows Mattias", "Root knows Johan", "Johan knows Emil", "Emil knows Peter", "Emil knows Tobias", "Tobias loves Sara"} )
@Test
public void shouldGetExpectedHitsWhenTraversingAtDepth()
throws PropertyValueException
{
Node start = getNode( "Root" );
String description = createJsonFrom( map(
"prune_evaluator",
map( "language", "builtin", "name", "none" ),
"return_filter",
map( "language", "javascript", "body",
"position.length()<3;" ) ) );
String entity = gen().expectedStatus( 200 ).payload( description ).post(
getTraverseUriNodes( start ) ).entity();
expectNodes( entity, getNodes( "Root", "Mattias", "Johan", "Emil" ) );
}
@Test
@Graph( "I know you" )
public void shouldGet400WhenSupplyingInvalidTraverserDescriptionFormat()
{
gen().expectedStatus( Status.BAD_REQUEST.getStatusCode() ).payload(
"::not JSON{[ at all" ).post(
getTraverseUriNodes( getNode( "I" ) ) ).entity();
}
@Test
@Graph( {"Root knows Mattias",
"Root knows Johan", "Johan knows Emil", "Emil knows Peter",
"Root eats Cork", "Cork hates Root",
"Root likes Banana", "Banana is_a Fruit"} )
public void shouldAllowTypeOrderedTraversals()
throws PropertyValueException
{
Node start = getNode( "Root" );
String description = createJsonFrom( map(
"expander", "order_by_type",
"relationships",
new Map[]{
map( "type", "eats"),
map( "type", "knows" ),
map( "type", "likes" )
},
"prune_evaluator",
map( "language", "builtin",
"name", "none" ),
"return_filter",
map( "language", "javascript",
"body", "position.length()<2;" )
) );
@SuppressWarnings( "unchecked" )
List<Map<String,Object>> nodes = (List<Map<String, Object>>) readJson( gen().expectedStatus( 200 ).payload(
description ).post(
getTraverseUriNodes( start ) ).entity() );
assertThat( nodes.size(), is( 5 ) );
assertThat( getName( nodes.get( 0 ) ), is( "Root" ) );
assertThat( getName( nodes.get( 1 ) ), is( "Cork" ) );
assertThat( getName( nodes.get( 2 ) ), is( "Mattias" ) );
assertThat( getName( nodes.get( 3 ) ), is( "Johan" ) );
assertThat( getName( nodes.get( 4 ) ), is( "Banana" ) );
}
@SuppressWarnings( "unchecked" )
private String getName( Map<String, Object> propContainer )
{
return (String) ((Map<String,Object>)propContainer.get( "data" )).get( "name" );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_TraverserDocIT.java
|
2,836
|
public class SetNodePropertiesDocIT extends
AbstractRestFunctionalTestBase
{
/**
* Update node properties.
*
* This will replace all existing properties on the node with the new set
* of attributes.
*/
@Graph( "jim knows joe" )
@Documented
@Test
public void shouldReturn204WhenPropertiesAreUpdated()
throws JsonParseException
{
Node jim = data.get().get( "jim" );
assertThat( jim, inTx(graphdb(), not( hasProperty( "age" ) ) ) );
gen.get().payload(
JsonHelper.createJsonFrom( MapUtil.map( "age", "18" ) ) ).expectedStatus(
204 ).put( getPropertiesUri( jim ) );
assertThat( jim, inTx(graphdb(), hasProperty( "age" ).withValue( "18" ) ) );
}
@Graph( "jim knows joe" )
@Test
public void set_node_properties_in_Unicode()
throws JsonParseException
{
Node jim = data.get().get( "jim" );
gen.get().payload(
JsonHelper.createJsonFrom( MapUtil.map( "name", "\u4f8b\u5b50" ) ) ).expectedStatus(
204 ).put( getPropertiesUri( jim ) );
assertThat( jim, inTx( graphdb(), hasProperty( "name" ).withValue( "\u4f8b\u5b50" ) ) );
}
@Test
@Graph( "jim knows joe" )
public void shouldReturn400WhenSendinIncompatibleJsonProperties()
throws JsonParseException
{
Map<String, Object> map = new HashMap<String, Object>();
map.put( "jim", new HashMap<String, Object>() );
gen.get().payload( JsonHelper.createJsonFrom( map ) ).expectedStatus(
400 ).put( getPropertiesUri( data.get().get( "jim" ) ) );
}
@Test
@Graph( "jim knows joe" )
public void shouldReturn400WhenSendingCorruptJsonProperties()
{
JaxRsResponse response = RestRequest.req().put(
getPropertiesUri( data.get().get( "jim" ) ),
"this:::Is::notJSON}" );
assertEquals( 400, response.getStatus() );
response.close();
}
@Test
@Graph( "jim knows joe" )
public void shouldReturn404WhenPropertiesSentToANodeWhichDoesNotExist()
throws JsonParseException
{
gen.get().payload(
JsonHelper.createJsonFrom( MapUtil.map( "key", "val" ) ) ).expectedStatus(
404 ).put( getDataUri() + "node/12345/properties" );
}
private URI getPropertyUri( Node node, String key ) throws Exception
{
return new URI( getPropertiesUri( node ) + "/" + key );
}
/**
* Set property on node.
*
* Setting different properties will retain the existing ones for this node.
* Note that a single value are submitted not as a map but just as a value
* (which is valid JSON) like in the example
* below.
*/
@Documented
@Graph( nodes = {@NODE(name="jim", properties={@PROP(key="foo2", value="bar2")})} )
@Test
public void shouldReturn204WhenPropertyIsSet() throws Exception
{
Node jim = data.get().get( "jim" );
gen.get().payload( JsonHelper.createJsonFrom( "bar" ) ).expectedStatus(
204 ).put( getPropertyUri( jim, "foo" ).toString() );
assertThat( jim, inTx(graphdb(), hasProperty( "foo" ) ) );
assertThat( jim, inTx(graphdb(), hasProperty( "foo2" ) ) );
}
/**
* Property values can not be nested.
*
* Nesting properties is not supported. You could for example store the
* nested JSON as a string instead.
*/
@Documented
@Test
public void shouldReturn400WhenSendinIncompatibleJsonProperty()
throws Exception
{
gen.get()
.noGraph()
.payload( "{\"foo\" : {\"bar\" : \"baz\"}}" )
.expectedStatus(
400 ).post( getDataUri() + "node/" );
}
@Test
@Graph( "jim knows joe" )
public void shouldReturn400WhenSendingCorruptJsonProperty()
throws Exception
{
JaxRsResponse response = RestRequest.req().put(
getPropertyUri( data.get().get( "jim" ), "foo" ),
"this:::Is::notJSON}" );
assertEquals( 400, response.getStatus() );
response.close();
}
@Test
@Graph( "jim knows joe" )
public void shouldReturn404WhenPropertySentToANodeWhichDoesNotExist()
throws Exception
{
JaxRsResponse response = RestRequest.req().put(
getDataUri() + "node/1234/foo",
JsonHelper.createJsonFrom( "bar" ) );
assertEquals( 404, response.getStatus() );
response.close();
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_SetNodePropertiesDocIT.java
|
2,837
|
public class SchemaIndexDocIT extends AbstractRestFunctionalTestBase
{
/**
* Create index.
*
* This will start a background job in the database that will create and populate the index.
* You can check the status of your index by listing all the indexes for the relevant label.
* The created index will show up, but have a state of +POPULATING+ until the index is ready,
* where it is marked as +ONLINE+.
*/
@Documented
@Test
@GraphDescription.Graph( nodes = {} )
public void create_index() throws PropertyValueException
{
data.get();
String labelName = "person", propertyKey = "name";
Map<String, Object> definition = map( "property_keys", asList( propertyKey ) );
String result = gen.get()
.noGraph()
.expectedStatus( 200 )
.payload( createJsonFrom( definition ) )
.post( getSchemaIndexLabelUri( labelName ) )
.entity();
Map<String, Object> serialized = jsonToMap( result );
assertEquals( labelName, serialized.get( "label" ) );
assertEquals( asList( propertyKey ), serialized.get( "property_keys" ) );
}
/**
* List indexes for a label.
*/
@Documented
@Test
@GraphDescription.Graph( nodes = {} )
public void get_indexes_for_label() throws PropertyValueException
{
data.get();
String labelName = "user", propertyKey = "name";
createIndex( labelName, propertyKey );
Map<String, Object> definition = map( "property_keys", asList( propertyKey ) );
String result = gen.get()
.noGraph()
.expectedStatus( 200 )
.payload( createJsonFrom( definition ) )
.get( getSchemaIndexLabelUri( labelName ) )
.entity();
List<Map<String, Object>> serializedList = jsonToList( result );
assertEquals( 1, serializedList.size() );
Map<String, Object> serialized = serializedList.get( 0 );
assertEquals( labelName, serialized.get( "label" ) );
assertEquals( asList( propertyKey ), serialized.get( "property_keys" ) );
}
/**
* Get all indexes.
*/
@SuppressWarnings( "unchecked" )
@Documented
@Test
@GraphDescription.Graph( nodes = {} )
public void get_indexes() throws PropertyValueException
{
data.get();
String labelName1 = "user", propertyKey1 = "name1";
String labelName2 = "prog", propertyKey2 = "name2";
createIndex( labelName1, propertyKey1 );
createIndex( labelName2, propertyKey2 );
String result = gen.get().noGraph().expectedStatus( 200 ).get( getSchemaIndexUri() ).entity();
List<Map<String, Object>> serializedList = jsonToList( result );
assertEquals( 2, serializedList.size() );
Set<String> labelNames = new HashSet<>();
Set<List<String>> propertyKeys = new HashSet<>();
Map<String, Object> serialized1 = serializedList.get( 0 );
labelNames.add( (String) serialized1.get( "label" ) );
propertyKeys.add( (List<String>) serialized1.get( "property_keys" ) );
Map<String, Object> serialized2 = serializedList.get( 1 );
labelNames.add( (String) serialized2.get( "label" ) );
propertyKeys.add( (List<String>) serialized2.get( "property_keys" ) );
assertEquals( asSet( labelName1, labelName2 ), labelNames );
assertEquals( asSet( asList( propertyKey1 ), asList( propertyKey2 ) ), propertyKeys );
}
/**
* Drop index
*/
@Documented
@Test
@GraphDescription.Graph( nodes = {} )
public void drop_index() throws Exception
{
data.get();
String labelName = "SomeLabel", propertyKey = "name";
IndexDefinition schemaIndex = createIndex( labelName, propertyKey );
assertThat( Neo4jMatchers.getIndexes( graphdb(), label( labelName ) ), containsOnly( schemaIndex ) );
gen.get()
.noGraph()
.expectedStatus( 204 )
.delete( getSchemaIndexLabelPropertyUri( labelName, propertyKey ) )
.entity();
assertThat( Neo4jMatchers.getIndexes( graphdb(), label( labelName ) ), not( containsOnly( schemaIndex ) ) );
}
/**
* Create an index for a label and property key which already exists.
*/
@Test
public void create_existing_index()
{
String labelName = "mylabel", propertyKey = "name";
createIndex( labelName, propertyKey );
Map<String, Object> definition = map( "property_keys", asList( propertyKey ) );
gen.get()
.noGraph()
.expectedStatus( 409 )
.payload( createJsonFrom( definition ) )
.post( getSchemaIndexLabelUri( labelName ) );
}
@Test
public void drop_non_existent_index() throws Exception
{
// GIVEN
String labelName = "ALabel", propertyKey = "name";
// WHEN
gen.get()
.expectedStatus( 404 )
.delete( getSchemaIndexLabelPropertyUri( labelName, propertyKey ) );
}
/**
* Creating a compound index should not yet be supported
*/
@Test
public void create_compound_index()
{
Map<String, Object> definition = map( "property_keys", asList( "first", "other" ) );
gen.get()
.noGraph()
.expectedStatus( 400 )
.payload( createJsonFrom( definition ) )
.post( getSchemaIndexLabelUri( "a_label" ) );
}
private IndexDefinition createIndex( String labelName, String propertyKey )
{
try ( Transaction tx = graphdb().beginTx() )
{
IndexDefinition indexDefinition = graphdb().schema().indexFor( label( labelName ) ).on( propertyKey )
.create();
tx.success();
return indexDefinition;
}
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_SchemaIndexDocIT.java
|
2,838
|
public class SchemaConstraintsDocIT extends AbstractRestFunctionalTestBase
{
/**
* Create uniqueness constraint.
* Create a uniqueness constraint on a property.
*/
@Documented
@Test
@GraphDescription.Graph( nodes = {} )
public void createPropertyUniquenessConstraint() throws PropertyValueException
{
data.get();
String labelName = "Person", propertyKey = "name";
Map<String, Object> definition = map( "property_keys", asList( propertyKey ) );
String result = gen.get().noGraph().expectedStatus( 200 ).payload( createJsonFrom( definition ) ).post(
getSchemaConstraintLabelUniquenessUri( labelName ) ).entity();
Map<String, Object> serialized = jsonToMap( result );
assertEquals( labelName, serialized.get( "label" ) );
assertEquals( ConstraintType.UNIQUENESS.name(), serialized.get( "type" ) );
assertEquals( asList( propertyKey ), serialized.get( "property_keys" ) );
}
/**
* Get a specific uniqueness constraint.
* Get a specific uniqueness constraint for a label and a property.
*/
@Documented
@Test
@GraphDescription.Graph( nodes = {} )
public void getLabelUniquenessPropertyConstraint() throws PropertyValueException
{
data.get();
String labelName = "User", propertyKey = "name";
createLabelUniquenessPropertyConstraint( labelName, propertyKey );
String result = gen.get().noGraph().expectedStatus( 200 ).get(
getSchemaConstraintLabelUniquenessPropertyUri( labelName, propertyKey ) ).entity();
List<Map<String, Object>> serializedList = jsonToList( result );
assertEquals( 1, serializedList.size() );
Map<String, Object> serialized = serializedList.get( 0 );
assertEquals( labelName, serialized.get( "label" ) );
assertEquals( ConstraintType.UNIQUENESS.name(), serialized.get( "type" ) );
assertEquals( asList( propertyKey ), serialized.get( "property_keys" ) );
}
/**
* Get all uniqueness constraints for a label.
*/
@SuppressWarnings( "unchecked" )
@Documented
@Test
@GraphDescription.Graph( nodes = {} )
public void getLabelUniquenessPropertyConstraints() throws PropertyValueException
{
data.get();
String labelName = "User", propertyKey1 = "name1", propertyKey2 = "name2";
createLabelUniquenessPropertyConstraint( labelName, propertyKey1 );
createLabelUniquenessPropertyConstraint( labelName, propertyKey2 );
String result = gen.get().noGraph().expectedStatus( 200 ).get( getSchemaConstraintLabelUniquenessUri( labelName ) ).entity();
List<Map<String, Object>> serializedList = jsonToList( result );
assertEquals( 2, serializedList.size() );
Map<String, Object> serialized1 = serializedList.get( 0 );
assertEquals( labelName, serialized1.get( "label" ) );
assertEquals( ConstraintType.UNIQUENESS.name(), serialized1.get( "type" ) );
List<String> keyList1 = (List<String>) serialized1.get( "property_keys" );
Map<String, Object> serialized2 = serializedList.get( 1 );
assertEquals( labelName, serialized2.get( "label" ) );
assertEquals( ConstraintType.UNIQUENESS.name(), serialized2.get( "type" ) );
List<String> keyList2 = (List<String>) serialized2.get( "property_keys" );
assertEquals( asSet( asList( propertyKey1 ), asList( propertyKey2 ) ), asSet( keyList1, keyList2 ) );
}
/**
* Get all constraints for a label.
*/
@SuppressWarnings( "unchecked" )
@Documented
@Test
@GraphDescription.Graph( nodes = {} )
public void getLabelPropertyConstraints() throws PropertyValueException
{
data.get();
String labelName = "User", propertyKey1 = "name1", propertyKey2 = "name2";
createLabelUniquenessPropertyConstraint( labelName, propertyKey1 );
createLabelUniquenessPropertyConstraint( labelName, propertyKey2 );
String result = gen.get().noGraph().expectedStatus( 200 ).get( getSchemaConstraintLabelUri( labelName ) ).entity();
List<Map<String, Object>> serializedList = jsonToList( result );
assertEquals( 2, serializedList.size() );
Map<String, Object> serialized1 = serializedList.get( 0 );
assertEquals( labelName, serialized1.get( "label" ) );
assertEquals( ConstraintType.UNIQUENESS.name(), serialized1.get( "type" ) );
List<String> keyList1 = (List<String>) serialized1.get( "property_keys" );
Map<String, Object> serialized2 = serializedList.get( 1 );
assertEquals( labelName, serialized2.get( "label" ) );
assertEquals( ConstraintType.UNIQUENESS.name(), serialized2.get( "type" ) );
List<String> keyList2 = (List<String>) serialized2.get( "property_keys" );
assertEquals( asSet( asList( propertyKey1 ), asList( propertyKey2 ) ), asSet( keyList1, keyList2 ) );
}
/**
* Get all constraints.
*/
@SuppressWarnings( "unchecked" )
@Documented
@Test
@GraphDescription.Graph( nodes = {} )
public void get_constraints() throws PropertyValueException
{
data.get();
String labelName1 = "User", propertyKey1 = "name1";
String labelName2 = "Prog", propertyKey2 = "name2";
createLabelUniquenessPropertyConstraint( labelName1, propertyKey1 );
createLabelUniquenessPropertyConstraint( labelName2, propertyKey2 );
String result = gen.get().noGraph().expectedStatus( 200 ).get( getSchemaConstraintUri() ).entity();
List<Map<String, Object>> serializedList = jsonToList( result );
assertEquals( 2, serializedList.size() );
Set<String> labelNames = new HashSet<>();
Set<List<String>> propertyKeys = new HashSet<>();
Map<String, Object> serialized1 = serializedList.get( 0 );
labelNames.add( (String) serialized1.get( "label" ) );
propertyKeys.add( (List<String>) serialized1.get( "property_keys" ) );
assertEquals( ConstraintType.UNIQUENESS.name(), serialized1.get( "type" ) );
Map<String, Object> serialized2 = serializedList.get( 1 );
labelNames.add( (String) serialized2.get( "label" ) );
propertyKeys.add( (List<String>) serialized2.get( "property_keys" ) );
assertEquals( ConstraintType.UNIQUENESS.name(), serialized2.get( "type" ) );
assertEquals( asSet( labelName1, labelName2 ), labelNames );
assertEquals( asSet( asList( propertyKey1 ), asList( propertyKey2 ) ), propertyKeys );
}
/**
* Drop constraint.
* Drop uniqueness constraint for a label and a property.
*/
@Documented
@Test
@GraphDescription.Graph( nodes = {} )
public void drop_constraint() throws Exception
{
data.get();
String labelName = "SomeLabel", propertyKey = "name";
ConstraintDefinition constraintDefinition = createLabelUniquenessPropertyConstraint( labelName,
propertyKey );
assertThat( getConstraints( graphdb(), label( labelName ) ), containsOnly( constraintDefinition ) );
gen.get().noGraph().expectedStatus( 204 ).delete( getSchemaConstraintLabelUniquenessPropertyUri( labelName, propertyKey ) ).entity();
assertThat( getConstraints( graphdb(), label( labelName ) ), isEmpty() );
}
/**
* Create an index for a label and property key which already exists.
*/
@Test
public void create_existing_constraint()
{
String labelName = "Mylabel", propertyKey = "name";
createLabelUniquenessPropertyConstraint( labelName, propertyKey );
}
@Test
public void drop_non_existent_constraint() throws Exception
{
// GIVEN
String labelName = "ALabel", propertyKey = "name";
// WHEN
gen.get().noGraph().expectedStatus( 404 ).delete( getSchemaConstraintLabelUniquenessPropertyUri( labelName, propertyKey ) );
}
/**
* Creating a compound index should not yet be supported.
*/
@Test
public void create_compound_schema_index()
{
Map<String, Object> definition = map( "property_keys", asList( "first", "other" ) );
gen.get().noGraph().expectedStatus( 400 ).payload( createJsonFrom( definition ) ).post(
getSchemaIndexLabelUri( "a_label" ) );
}
private ConstraintDefinition createLabelUniquenessPropertyConstraint( String labelName, String propertyKey )
{
try ( Transaction tx = graphdb().beginTx() )
{
ConstraintDefinition constraintDefinition = graphdb().schema().constraintFor( label( labelName ) )
.assertPropertyIsUnique( propertyKey ).create();
tx.success();
return constraintDefinition;
}
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_SchemaConstraintsDocIT.java
|
2,839
|
public class RetrieveRelationshipsFromNodeDocIT extends AbstractRestFunctionalTestBase
{
private long nodeWithRelationships;
private long nodeWithoutRelationships;
private long nonExistingNode;
private static FunctionalTestHelper functionalTestHelper;
private static GraphDbHelper helper;
private long likes;
@BeforeClass
public static void setupServer() throws IOException
{
functionalTestHelper = new FunctionalTestHelper( server() );
helper = functionalTestHelper.getGraphDbHelper();
}
@Before
public void setupTheDatabase()
{
cleanDatabase();
createSimpleGraph();
}
private void createSimpleGraph()
{
nodeWithRelationships = helper.createNode();
likes = helper.createRelationship( "LIKES", nodeWithRelationships, helper.createNode() );
helper.createRelationship( "LIKES", helper.createNode(), nodeWithRelationships );
helper.createRelationship( "HATES", nodeWithRelationships, helper.createNode() );
nodeWithoutRelationships = helper.createNode();
nonExistingNode = nodeWithoutRelationships * 100;
}
private JaxRsResponse sendRetrieveRequestToServer( long nodeId, String path )
{
return RestRequest.req().get( functionalTestHelper.nodeUri() + "/" + nodeId + "/relationships" + path );
}
private void verifyRelReps( int expectedSize, String json ) throws JsonParseException
{
List<Map<String, Object>> relreps = JsonHelper.jsonToList( json );
assertEquals( expectedSize, relreps.size() );
for ( Map<String, Object> relrep : relreps )
{
RelationshipRepresentationTest.verifySerialisation( relrep );
}
}
@Test
public void shouldParameteriseUrisInRelationshipRepresentationWithHostHeaderValue() throws Exception
{
HttpClient httpclient = new DefaultHttpClient();
try
{
HttpGet httpget = new HttpGet( "http://localhost:7474/db/data/relationship/" + likes );
httpget.setHeader( "Accept", "application/json" );
httpget.setHeader( "Host", "dummy.neo4j.org" );
HttpResponse response = httpclient.execute( httpget );
HttpEntity entity = response.getEntity();
String entityBody = IOUtils.toString( entity.getContent(), "UTF-8" );
System.out.println( entityBody );
assertThat( entityBody, containsString( "http://dummy.neo4j.org/db/data/relationship/" + likes ) );
assertThat( entityBody, not( containsString( "localhost:7474" ) ) );
}
finally
{
httpclient.getConnectionManager().shutdown();
}
}
@Test
public void shouldParameteriseUrisInRelationshipRepresentationWithoutHostHeaderUsingRequestUri() throws Exception
{
HttpClient httpclient = new DefaultHttpClient();
try
{
HttpGet httpget = new HttpGet( "http://localhost:7474/db/data/relationship/" + likes );
httpget.setHeader( "Accept", "application/json" );
HttpResponse response = httpclient.execute( httpget );
HttpEntity entity = response.getEntity();
String entityBody = IOUtils.toString( entity.getContent(), "UTF-8" );
assertThat( entityBody, containsString( "http://localhost:7474/db/data/relationship/" + likes ) );
}
finally
{
httpclient.getConnectionManager().shutdown();
}
}
/**
* Get all relationships.
*/
@Documented
@Test
public void shouldRespondWith200AndListOfRelationshipRepresentationsWhenGettingAllRelationshipsForANode()
throws JsonParseException
{
String entity = gen.get()
.expectedStatus( 200 )
.get( functionalTestHelper.nodeUri() + "/" + nodeWithRelationships + "/relationships" + "/all" )
.entity();
verifyRelReps( 3, entity );
}
@Test
public void shouldRespondWith200AndListOfRelationshipRepresentationsWhenGettingAllRelationshipsForANodeStreaming()
throws JsonParseException
{
String entity = gen.get()
.withHeader(StreamingJsonFormat.STREAM_HEADER,"true")
.expectedStatus(200)
.get( functionalTestHelper.nodeUri() + "/" + nodeWithRelationships + "/relationships" + "/all" )
.entity();
verifyRelReps( 3, entity );
}
/**
* Get incoming relationships.
*/
@Documented
@Test
public void shouldRespondWith200AndListOfRelationshipRepresentationsWhenGettingIncomingRelationshipsForANode()
throws JsonParseException
{
String entity = gen.get()
.expectedStatus( 200 )
.get( functionalTestHelper.nodeUri() + "/" + nodeWithRelationships + "/relationships" + "/in" )
.entity();
verifyRelReps( 1, entity );
}
/**
* Get outgoing relationships.
*/
@Documented
@Test
public void shouldRespondWith200AndListOfRelationshipRepresentationsWhenGettingOutgoingRelationshipsForANode()
throws JsonParseException
{
String entity = gen.get()
.expectedStatus( 200 )
.get( functionalTestHelper.nodeUri() + "/" + nodeWithRelationships + "/relationships" + "/out" )
.entity();
verifyRelReps( 2, entity );
}
/**
* Get typed relationships.
*
* Note that the "+&+" needs to be encoded like "+%26+" for example when
* using http://curl.haxx.se/[cURL] from the terminal.
*/
@Documented
@Test
public void shouldRespondWith200AndListOfRelationshipRepresentationsWhenGettingAllTypedRelationshipsForANode()
throws JsonParseException
{
String entity = gen.get()
.expectedStatus( 200 )
.get( functionalTestHelper.nodeUri() + "/" + nodeWithRelationships + "/relationships"
+ "/all/LIKES&HATES" )
.entity();
verifyRelReps( 3, entity );
}
@Test
public void shouldRespondWith200AndListOfRelationshipRepresentationsWhenGettingIncomingTypedRelationshipsForANode()
throws JsonParseException
{
JaxRsResponse response = sendRetrieveRequestToServer( nodeWithRelationships, "/in/LIKES" );
assertEquals( 200, response.getStatus() );
assertThat( response.getType().toString(), containsString( MediaType.APPLICATION_JSON ) );
verifyRelReps( 1, response.getEntity() );
response.close();
}
@Test
public void shouldRespondWith200AndListOfRelationshipRepresentationsWhenGettingOutgoingTypedRelationshipsForANode()
throws JsonParseException
{
JaxRsResponse response = sendRetrieveRequestToServer( nodeWithRelationships, "/out/HATES" );
assertEquals( 200, response.getStatus() );
assertThat( response.getType().toString(), containsString( MediaType.APPLICATION_JSON ) );
verifyRelReps( 1, response.getEntity() );
response.close();
}
/**
* Get relationships on a node without relationships.
*/
@Documented
@Test
public void shouldRespondWith200AndEmptyListOfRelationshipRepresentationsWhenGettingAllRelationshipsForANodeWithoutRelationships()
throws JsonParseException
{
String entity = gen.get()
.expectedStatus( 200 )
.get( functionalTestHelper.nodeUri() + "/" + nodeWithoutRelationships + "/relationships" + "/all" )
.entity();
verifyRelReps( 0, entity );
}
@Test
public void shouldRespondWith200AndEmptyListOfRelationshipRepresentationsWhenGettingIncomingRelationshipsForANodeWithoutRelationships()
throws JsonParseException
{
JaxRsResponse response = sendRetrieveRequestToServer( nodeWithoutRelationships, "/in" );
assertEquals( 200, response.getStatus() );
assertThat( response.getType().toString(), containsString( MediaType.APPLICATION_JSON ) );
verifyRelReps( 0, response.getEntity() );
response.close();
}
@Test
public void shouldRespondWith200AndEmptyListOfRelationshipRepresentationsWhenGettingOutgoingRelationshipsForANodeWithoutRelationships()
throws JsonParseException
{
JaxRsResponse response = sendRetrieveRequestToServer( nodeWithoutRelationships, "/out" );
assertEquals( 200, response.getStatus() );
assertThat( response.getType().toString(), containsString( MediaType.APPLICATION_JSON ) );
verifyRelReps( 0, response.getEntity() );
response.close();
}
@Test
public void shouldRespondWith404WhenGettingAllRelationshipsForNonExistingNode()
{
JaxRsResponse response = sendRetrieveRequestToServer( nonExistingNode, "/all" );
assertEquals( 404, response.getStatus() );
response.close();
}
@Test
public void shouldRespondWith404WhenGettingIncomingRelationshipsForNonExistingNode()
{
JaxRsResponse response = sendRetrieveRequestToServer( nonExistingNode, "/in" );
assertEquals( 404, response.getStatus() );
response.close();
}
@Test
public void shouldRespondWith404WhenGettingIncomingRelationshipsForNonExistingNodeStreaming()
{
JaxRsResponse response = RestRequest.req().header(StreamingJsonFormat.STREAM_HEADER,"true").get(functionalTestHelper.nodeUri() + "/" + nonExistingNode + "/relationships" + "/in");
assertEquals( 404, response.getStatus() );
response.close();
}
@Test
public void shouldRespondWith404WhenGettingOutgoingRelationshipsForNonExistingNode()
{
JaxRsResponse response = sendRetrieveRequestToServer( nonExistingNode, "/out" );
assertEquals( 404, response.getStatus() );
response.close();
}
@Test
public void shouldGet200WhenRetrievingValidRelationship()
{
long relationshipId = helper.createRelationship( "LIKES" );
JaxRsResponse response = RestRequest.req().get( functionalTestHelper.relationshipUri( relationshipId ) );
assertEquals( 200, response.getStatus() );
response.close();
}
@Test
public void shouldGetARelationshipRepresentationInJsonWhenRetrievingValidRelationship() throws Exception
{
long relationshipId = helper.createRelationship( "LIKES" );
JaxRsResponse response = RestRequest.req().get( functionalTestHelper.relationshipUri( relationshipId ) );
String entity = response.getEntity();
assertNotNull( entity );
isLegalJson( entity );
response.close();
}
private void isLegalJson( String entity ) throws IOException, JsonParseException
{
JsonHelper.jsonToMap( entity );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_RetrieveRelationshipsFromNodeDocIT.java
|
2,840
|
public class RetrieveNodeDocIT extends AbstractRestFunctionalTestBase
{
private URI nodeUri;
private static FunctionalTestHelper functionalTestHelper;
@BeforeClass
public static void setupServer() throws IOException
{
functionalTestHelper = new FunctionalTestHelper( server() );
}
@Before
public void cleanTheDatabaseAndInitialiseTheNodeUri() throws Exception
{
cleanDatabase();
nodeUri = new URI( functionalTestHelper.nodeUri() + "/"
+ new GraphDbHelper( server().getDatabase() ).createNode() );
}
@Test
public void shouldParameteriseUrisInNodeRepresentationWithHostHeaderValue() throws Exception
{
HttpClient httpclient = new DefaultHttpClient();
try
{
HttpGet httpget = new HttpGet( nodeUri );
httpget.setHeader( "Accept", "application/json" );
httpget.setHeader( "Host", "dummy.neo4j.org" );
HttpResponse response = httpclient.execute( httpget );
HttpEntity entity = response.getEntity();
String entityBody = IOUtils.toString( entity.getContent(), "UTF-8" );
assertThat( entityBody, containsString( "http://dummy.neo4j.org/db/data/node/" ) );
} finally
{
httpclient.getConnectionManager().shutdown();
}
}
@Test
public void shouldParameteriseUrisInNodeRepresentationWithoutHostHeaderUsingRequestUri() throws Exception
{
HttpClient httpclient = new DefaultHttpClient();
try
{
HttpGet httpget = new HttpGet( nodeUri );
httpget.setHeader( "Accept", "application/json" );
HttpResponse response = httpclient.execute( httpget );
HttpEntity entity = response.getEntity();
String entityBody = IOUtils.toString( entity.getContent(), "UTF-8" );
assertThat( entityBody, containsString( nodeUri.toString() ) );
} finally
{
httpclient.getConnectionManager().shutdown();
}
}
/**
* Get node.
*
* Note that the response contains URI/templates for the available
* operations for getting properties and relationships.
*/
@Documented
@Test
public void shouldGet200WhenRetrievingNode() throws Exception
{
String uri = nodeUri.toString();
gen.get()
.expectedStatus( 200 )
.get( uri );
}
/**
* Get node -- compact.
*
* Specifying the subformat in the requests media type yields a more compact
* JSON response without metadata and templates.
*/
@Documented
@Test
public void shouldGet200WhenRetrievingNodeCompact()
{
String uri = nodeUri.toString();
ResponseEntity entity = gen.get()
.expectedType( CompactJsonFormat.MEDIA_TYPE )
.expectedStatus( 200 )
.get( uri );
assertTrue( entity.entity()
.contains( "self" ) );
}
@Test
public void shouldGetContentLengthHeaderWhenRetrievingNode() throws Exception
{
JaxRsResponse response = retrieveNodeFromService( nodeUri.toString() );
assertNotNull( response.getHeaders()
.get( "Content-Length" ) );
response.close();
}
@Test
public void shouldHaveJsonMediaTypeOnResponse()
{
JaxRsResponse response = retrieveNodeFromService( nodeUri.toString() );
assertThat( response.getType().toString(), containsString( MediaType.APPLICATION_JSON ) );
response.close();
}
@Test
public void shouldHaveJsonDataInResponse() throws Exception
{
JaxRsResponse response = retrieveNodeFromService( nodeUri.toString() );
Map<String, Object> map = JsonHelper.jsonToMap( response.getEntity() );
assertTrue( map.containsKey( "self" ) );
response.close();
}
/**
* Get non-existent node.
*/
@Documented
@Test
public void shouldGet404WhenRetrievingNonExistentNode() throws Exception
{
gen.get()
.expectedStatus( 404 )
.get( nodeUri + "00000" );
}
private JaxRsResponse retrieveNodeFromService( final String uri )
{
return RestRequest.req().get( uri );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_RetrieveNodeDocIT.java
|
2,841
|
public class RestRequest {
private final URI baseUri;
private final static Client DEFAULT_CLIENT = Client.create();
private final Client client;
private MediaType accept = MediaType.APPLICATION_JSON_TYPE;
private Map<String, String> headers=new HashMap<String, String>();
public RestRequest( URI baseUri ) {
this( baseUri, null, null );
}
public RestRequest( URI baseUri, String username, String password ) {
this.baseUri = uriWithoutSlash( baseUri );
if ( username != null )
{
client = Client.create();
client.addFilter( new HTTPBasicAuthFilter( username, password ) );
}
else
{
client = DEFAULT_CLIENT;
}
}
public RestRequest(URI uri, Client client) {
this.baseUri = uriWithoutSlash( uri );
this.client = client;
}
public RestRequest() {
this( null );
}
private URI uriWithoutSlash( URI uri ) {
if (uri == null) return null;
String uriString = uri.toString();
return uriString.endsWith( "/" ) ? uri( uriString.substring( 0, uriString.length() - 1 ) ) : uri;
}
public static String encode( Object value ) {
if ( value == null ) return "";
try {
return URLEncoder.encode( value.toString(), "utf-8" ).replaceAll( "\\+", "%20" );
} catch ( UnsupportedEncodingException e ) {
throw new RuntimeException( e );
}
}
private Builder builder( String path ) {
return builder( path, accept );
}
private Builder builder( String path, final MediaType accept ) {
WebResource resource = client.resource( uri( pathOrAbsolute( path ) ) );
Builder builder = resource.accept( accept );
if ( !headers.isEmpty() ) {
for ( Map.Entry<String, String> header : headers.entrySet() ) {
builder = builder.header( header.getKey(),header.getValue() );
}
}
return builder;
}
private String pathOrAbsolute( String path ) {
if ( path.startsWith( "http://" ) ) return path;
return baseUri + "/" + path;
}
public JaxRsResponse get( String path ) {
return JaxRsResponse.extractFrom( HTTP.sanityCheck( builder( path ).get( ClientResponse.class ) ) );
}
public JaxRsResponse get(String path, String data) {
return get( path, data, MediaType.APPLICATION_JSON_TYPE );
}
public JaxRsResponse get( String path, String data, final MediaType mediaType ) {
Builder builder = builder( path );
if ( data != null ) {
builder = builder.entity( data, mediaType);
} else {
builder = builder.type( mediaType );
}
return JaxRsResponse.extractFrom( HTTP.sanityCheck( builder.get( ClientResponse.class ) ) );
}
public JaxRsResponse delete(String path) {
return JaxRsResponse.extractFrom( HTTP.sanityCheck( builder( path ).delete( ClientResponse.class ) ) );
}
public JaxRsResponse post(String path, String data) {
return post(path, data, MediaType.APPLICATION_JSON_TYPE);
}
public JaxRsResponse post(String path, String data, final MediaType mediaType) {
Builder builder = builder( path );
if ( data != null ) {
builder = builder.entity( data, mediaType);
} else {
builder = builder.type(mediaType);
}
return JaxRsResponse.extractFrom( HTTP.sanityCheck( builder.post( ClientResponse.class ) ) );
}
public JaxRsResponse put(String path, String data) {
Builder builder = builder( path );
if ( data != null ) {
builder = builder.entity( data, MediaType.APPLICATION_JSON_TYPE );
}
return new JaxRsResponse( HTTP.sanityCheck( builder.put( ClientResponse.class ) ) );
}
public Object toEntity( JaxRsResponse JaxRsResponse ) throws PropertyValueException {
return JsonHelper.jsonToSingleValue( entityString( JaxRsResponse ) );
}
public Map<?, ?> toMap( JaxRsResponse JaxRsResponse) throws JsonParseException {
final String json = entityString( JaxRsResponse );
return JsonHelper.jsonToMap(json);
}
private String entityString( JaxRsResponse JaxRsResponse) {
return JaxRsResponse.getEntity();
}
public boolean statusIs( JaxRsResponse JaxRsResponse, Response.StatusType status ) {
return JaxRsResponse.getStatus() == status.getStatusCode();
}
public boolean statusOtherThan( JaxRsResponse JaxRsResponse, Response.StatusType status ) {
return !statusIs(JaxRsResponse, status );
}
public RestRequest with( String uri ) {
return new RestRequest( uri( uri ), client );
}
private URI uri( String uri ) {
try {
return new URI( uri );
} catch ( URISyntaxException e ) {
throw new RuntimeException( e );
}
}
public URI getUri() {
return baseUri;
}
public JaxRsResponse get() {
return get( "" );
}
public JaxRsResponse get(String path, final MediaType acceptType) {
Builder builder = builder(path, acceptType);
return JaxRsResponse.extractFrom( HTTP.sanityCheck( builder.get( ClientResponse.class ) ) );
}
public static RestRequest req() {
return new RestRequest();
}
public JaxRsResponse delete(URI location) {
return delete(location.toString());
}
public JaxRsResponse put(URI uri, String data) {
return put(uri.toString(),data);
}
public RestRequest accept( MediaType accept )
{
this.accept = accept;
return this;
}
public RestRequest header(String header, String value) {
this.headers.put(header,value);
return this;
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_RestRequest.java
|
2,842
|
public class RemoveRelationshipDocIT extends AbstractRestFunctionalTestBase
{
private static FunctionalTestHelper functionalTestHelper;
private static GraphDbHelper helper;
@BeforeClass
public static void setupServer() throws IOException
{
functionalTestHelper = new FunctionalTestHelper( server() );
helper = functionalTestHelper.getGraphDbHelper();
}
@Before
public void cleanTheDatabase()
{
cleanDatabase();
}
@Test
public void shouldGet204WhenRemovingAValidRelationship() throws Exception
{
long relationshipId = helper.createRelationship( "KNOWS" );
JaxRsResponse response = sendDeleteRequest(new URI(functionalTestHelper.relationshipUri(relationshipId)));
assertEquals( 204, response.getStatus() );
response.close();
}
@Test
public void shouldGet404WhenRemovingAnInvalidRelationship() throws Exception
{
long relationshipId = helper.createRelationship( "KNOWS" );
JaxRsResponse response = sendDeleteRequest(new URI(
functionalTestHelper.relationshipUri((relationshipId + 1) * 9999)));
assertEquals( 404, response.getStatus() );
response.close();
}
private JaxRsResponse sendDeleteRequest(URI requestUri)
{
return RestRequest.req().delete(requestUri);
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_RemoveRelationshipDocIT.java
|
2,843
|
public class RemoveNodePropertiesDocIT extends AbstractRestFunctionalTestBase
{
private static FunctionalTestHelper functionalTestHelper;
private static GraphDbHelper helper;
@BeforeClass
public static void setupServer() throws IOException
{
functionalTestHelper = new FunctionalTestHelper( server() );
helper = functionalTestHelper.getGraphDbHelper();
}
@Before
public void cleanTheDatabase()
{
cleanDatabase();
}
private String getPropertiesUri( final long nodeId )
{
return functionalTestHelper.nodePropertiesUri( nodeId );
}
@Test
public void shouldReturn204WhenPropertiesAreRemoved()
{
long nodeId = helper.createNode();
Map<String, Object> map = new HashMap<String, Object>();
map.put( "jim", "tobias" );
helper.setNodeProperties( nodeId, map );
JaxRsResponse response = removeNodePropertiesOnServer(nodeId);
assertEquals( 204, response.getStatus() );
response.close();
}
/**
* Delete all properties from node.
*/
@Documented
@Test
public void shouldReturn204WhenAllPropertiesAreRemoved()
{
long nodeId = helper.createNode();
Map<String, Object> map = new HashMap<String, Object>();
map.put( "jim", "tobias" );
helper.setNodeProperties( nodeId, map );
gen.get()
.expectedStatus( 204 )
.delete( functionalTestHelper.nodePropertiesUri( nodeId ) );
}
@Test
public void shouldReturn404WhenPropertiesSentToANodeWhichDoesNotExist() {
JaxRsResponse response = RestRequest.req().delete(getPropertiesUri(999999));
assertEquals(404, response.getStatus());
response.close();
}
private JaxRsResponse removeNodePropertiesOnServer(final long nodeId)
{
return RestRequest.req().delete(getPropertiesUri(nodeId));
}
/**
* To delete a single property
* from a node, see the example below.
*/
@Documented
@Test
public void delete_a_named_property_from_a_node()
{
long nodeId = helper.createNode();
Map<String, Object> map = new HashMap<String, Object>();
map.put( "name", "tobias" );
helper.setNodeProperties( nodeId, map );
gen.get()
.expectedStatus( 204 )
.description( startGraph( "delete named property start" ))
.delete( functionalTestHelper.nodePropertyUri( nodeId, "name") );
}
@Test
public void shouldReturn404WhenRemovingNonExistingNodeProperty()
{
long nodeId = helper.createNode();
Map<String, Object> map = new HashMap<String, Object>();
map.put( "jim", "tobias" );
helper.setNodeProperties( nodeId, map );
JaxRsResponse response = removeNodePropertyOnServer(nodeId, "foo");
assertEquals(404, response.getStatus());
}
@Test
public void shouldReturn404WhenPropertySentToANodeWhichDoesNotExist() {
JaxRsResponse response = RestRequest.req().delete(getPropertyUri(999999, "foo"));
assertEquals(404, response.getStatus());
}
private String getPropertyUri( final long nodeId, final String key )
{
return functionalTestHelper.nodePropertyUri( nodeId, key );
}
private JaxRsResponse removeNodePropertyOnServer(final long nodeId, final String key)
{
return RestRequest.req().delete(getPropertyUri(nodeId, key));
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_RemoveNodePropertiesDocIT.java
|
2,844
|
public class RelationshipDocIT extends AbstractRestFunctionalTestBase
{
private static FunctionalTestHelper functionalTestHelper;
@BeforeClass
public static void setupServer() throws IOException
{
functionalTestHelper = new FunctionalTestHelper( server() );
}
@Test
@Graph(nodes = {@NODE(name = "Romeo", setNameProperty = true),
@NODE(name = "Juliet", setNameProperty = true)}, relationships = {@REL(start = "Romeo", end = "Juliet",
type = "LOVES", properties = {@PROP(key = "cost", value = "high", type = GraphDescription.PropType
.STRING)})})
@Title("Remove properties from a relationship")
public void shouldReturn204WhenPropertiesAreRemovedFromRelationship()
{
Relationship loves = getFirstRelationshipFromRomeoNode();
gen().expectedStatus( Status.NO_CONTENT.getStatusCode() ).delete(
functionalTestHelper.relationshipPropertiesUri( loves.getId() ) )
.entity();
}
@Test
@Graph("I know you")
public void get_Relationship_by_ID() throws JsonParseException
{
Node node = data.get().get( "I" );
Relationship relationship;
try ( Transaction transaction = node.getGraphDatabase().beginTx() )
{
relationship = node.getSingleRelationship(
DynamicRelationshipType.withName( "know" ),
Direction.OUTGOING );
}
String response = gen().expectedStatus(
com.sun.jersey.api.client.ClientResponse.Status.OK.getStatusCode() ).get(
getRelationshipUri( relationship ) ).entity();
assertTrue( JsonHelper.jsonToMap( response ).containsKey( "start" ) );
}
/**
* See the example request below.
*/
@Test
@Documented
@Graph(nodes = {@NODE(name = "Romeo", setNameProperty = true),
@NODE(name = "Juliet", setNameProperty = true)}, relationships = {@REL(start = "Romeo", end = "Juliet",
type = "LOVES", properties = {@PROP(key = "cost", value = "high", type = GraphDescription.PropType
.STRING)})})
@Title("Remove property from a relationship")
public void shouldReturn204WhenPropertyIsRemovedFromRelationship()
{
data.get();
Relationship loves = getFirstRelationshipFromRomeoNode();
gen().description(
startGraph( "Remove property from a relationship1" ) );
gen().expectedStatus( Status.NO_CONTENT.getStatusCode() ).delete(
getPropertiesUri( loves ) + "/cost" ).entity();
}
/**
* Attempting to remove a property that doesn't exist results in
* an error.
*/
@Test
@Documented
@Title("Remove non-existent property from a relationship")
@Graph(nodes = {@NODE(name = "Romeo", setNameProperty = true),
@NODE(name = "Juliet", setNameProperty = true)}, relationships = {@REL(start = "Romeo", end = "Juliet",
type = "LOVES", properties = {@PROP(key = "cost", value = "high", type = GraphDescription.PropType
.STRING)})})
public void shouldReturn404WhenPropertyWhichDoesNotExistRemovedFromRelationship()
{
data.get();
Relationship loves = getFirstRelationshipFromRomeoNode();
gen().expectedStatus( Status.NOT_FOUND.getStatusCode() ).delete(
getPropertiesUri( loves ) + "/non-existent" ).entity();
}
@Test
@Graph(nodes = {@NODE(name = "Romeo", setNameProperty = true),
@NODE(name = "Juliet", setNameProperty = true)}, relationships = {@REL(start = "Romeo", end = "Juliet",
type = "LOVES", properties = {@PROP(key = "cost", value = "high", type = GraphDescription.PropType
.STRING)})})
public void shouldReturn404WhenPropertyWhichDoesNotExistRemovedFromRelationshipStreaming()
{
data.get();
Relationship loves = getFirstRelationshipFromRomeoNode();
gen().withHeader( StreamingFormat.STREAM_HEADER, "true" ).expectedStatus( Status.NOT_FOUND.getStatusCode
() ).delete(
getPropertiesUri( loves ) + "/non-existent" ).entity();
}
/**
* Attempting to remove all properties from a relationship which doesn't
* exist results in an error.
*/
@Test
@Graph("I know you")
@Documented
@Title("Remove properties from a non-existing relationship")
public void shouldReturn404WhenPropertiesRemovedFromARelationshipWhichDoesNotExist()
{
data.get();
gen().expectedStatus( Status.NOT_FOUND.getStatusCode() )
.delete( functionalTestHelper.relationshipPropertiesUri( 1234L ) )
.entity();
}
/**
* Attempting to remove a property from a relationship which doesn't exist
* results in an error.
*/
@Test
@Graph("I know you")
@Documented
@Title("Remove property from a non-existing relationship")
public void shouldReturn404WhenPropertyRemovedFromARelationshipWhichDoesNotExist()
{
data.get();
gen().expectedStatus( Status.NOT_FOUND.getStatusCode() )
.delete(
functionalTestHelper.relationshipPropertiesUri( 1234L )
+ "/cost" )
.entity();
}
@Test
@Graph(nodes = {@NODE(name = "Romeo", setNameProperty = true),
@NODE(name = "Juliet", setNameProperty = true)}, relationships = {@REL(start = "Romeo", end = "Juliet",
type = "LOVES", properties = {@PROP(key = "cost", value = "high", type = GraphDescription.PropType
.STRING)})})
@Title("Delete relationship")
public void removeRelationship()
{
data.get();
Relationship loves = getFirstRelationshipFromRomeoNode();
gen().description( startGraph( "Delete relationship1" ) );
gen().expectedStatus( Status.NO_CONTENT.getStatusCode() ).delete(
getRelationshipUri( loves ) ).entity();
}
@Test
@Graph(nodes = {@NODE(name = "Romeo", setNameProperty = true),
@NODE(name = "Juliet", setNameProperty = true)}, relationships = {@REL(start = "Romeo", end = "Juliet",
type = "LOVES", properties = {@PROP(key = "cost", value = "high", type = GraphDescription.PropType
.STRING)})})
public void get_single_property_on_a_relationship() throws Exception
{
Relationship loves = getFirstRelationshipFromRomeoNode();
String response = gen().expectedStatus( ClientResponse.Status.OK ).get( getRelPropURI( loves,
"cost" ) ).entity();
assertTrue( response.contains( "high" ) );
}
private String getRelPropURI( Relationship loves, String propertyKey )
{
return getRelationshipUri( loves ) + "/properties/" + propertyKey;
}
@Test
@Graph(nodes = {@NODE(name = "Romeo", setNameProperty = true),
@NODE(name = "Juliet", setNameProperty = true)}, relationships = {@REL(start = "Romeo", end = "Juliet",
type = "LOVES", properties = {@PROP(key = "cost", value = "high", type = GraphDescription.PropType
.STRING)})})
public void set_single_property_on_a_relationship() throws Exception
{
Relationship loves = getFirstRelationshipFromRomeoNode();
assertThat( loves, inTx( graphdb(), hasProperty( "cost" ).withValue( "high" ) ) );
gen().description( startGraph( "Set relationship property1" ) );
gen().expectedStatus( ClientResponse.Status.NO_CONTENT ).payload( "\"deadly\"" ).put( getRelPropURI( loves,
"cost" ) ).entity();
assertThat( loves, inTx( graphdb(), hasProperty( "cost" ).withValue( "deadly" ) ) );
}
@Test
@Graph(nodes = {@NODE(name = "Romeo", setNameProperty = true),
@NODE(name = "Juliet", setNameProperty = true)}, relationships = {@REL(start = "Romeo", end = "Juliet",
type = "LOVES", properties = {@PROP(key = "cost", value = "high", type = GraphDescription.PropType
.STRING), @PROP(key = "since", value = "1day", type = GraphDescription.PropType.STRING)})})
public void set_all_properties_on_a_relationship() throws Exception
{
Relationship loves = getFirstRelationshipFromRomeoNode();
assertThat( loves, inTx( graphdb(), hasProperty( "cost" ).withValue( "high" ) ) );
gen().description( startGraph( "Set relationship property1" ) );
gen().expectedStatus( ClientResponse.Status.NO_CONTENT ).payload( JsonHelper.createJsonFrom( MapUtil.map(
"happy", false ) ) ).put( getRelPropsURI( loves ) ).entity();
assertThat( loves, inTx( graphdb(), hasProperty( "happy" ).withValue( false ) ) );
assertThat( loves, inTx( graphdb(), not( hasProperty( "cost" ) ) ) );
}
@Test
@Graph(nodes = {@NODE(name = "Romeo", setNameProperty = true),
@NODE(name = "Juliet", setNameProperty = true)}, relationships = {@REL(start = "Romeo", end = "Juliet",
type = "LOVES", properties = {@PROP(key = "cost", value = "high", type = GraphDescription.PropType
.STRING), @PROP(key = "since", value = "1day", type = GraphDescription.PropType.STRING)})})
public void get_all_properties_on_a_relationship() throws Exception
{
Relationship loves = getFirstRelationshipFromRomeoNode();
String response = gen().expectedStatus( ClientResponse.Status.OK ).get( getRelPropsURI( loves ) ).entity();
assertTrue( response.contains( "high" ) );
}
private Relationship getFirstRelationshipFromRomeoNode()
{
Node romeo = getNode( "Romeo" );
try ( Transaction transaction = romeo.getGraphDatabase().beginTx() )
{
return romeo.getRelationships().iterator().next();
}
}
private String getRelPropsURI( Relationship rel )
{
return getRelationshipUri( rel ) + "/properties";
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_RelationshipDocIT.java
|
2,845
|
public class RedirectorDocIT extends AbstractRestFunctionalTestBase
{
@Before
public void cleanTheDatabase()
{
cleanDatabase();
}
@Test
public void shouldRedirectRootToWebadmin() throws Exception {
JaxRsResponse response = new RestRequest(server().baseUri()).get();
assertThat(response.getStatus(), is(not(404)));
}
@Test
public void shouldNotRedirectTheRestOfTheWorld() throws Exception {
JaxRsResponse response = new RestRequest(server().baseUri()).get("a/different/relative/webadmin/data/uri/");
assertThat(response.getStatus(), is(404));
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_RedirectorDocIT.java
|
2,846
|
public static class ResponseEntity
{
private final String entity;
private final JaxRsResponse response;
public ResponseEntity( ClientResponse response, String entity )
{
this.response = new JaxRsResponse(response,entity);
this.entity = entity;
}
/**
* The response entity as a String.
*/
public String entity()
{
return entity;
}
/**
* Note that the response object returned does not give access to the
* response entity.
*/
public JaxRsResponse response()
{
return response;
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_RESTDocsGenerator.java
|
2,847
|
{
@Override
public RESTDocsGenerator create( GraphDefinition graph, String title, String documentation )
{
RESTDocsGenerator gen = RESTDocsGenerator.create( title );
gen.description(documentation);
return gen;
}
@Override
public void destroy( RESTDocsGenerator product, boolean successful )
{
// TODO: invoke some complete method here?
}
};
| false
|
community_server_src_test_java_org_neo4j_server_rest_RESTDocsGenerator.java
|
2,848
|
public class RESTDocsGenerator extends AsciiDocGenerator
{
private static final String EQUAL_SIGNS = "======";
private static final Builder REQUEST_BUILDER = ClientRequest.create();
private static final List<String> RESPONSE_HEADERS = Arrays.asList( "Content-Type", "Location" );
private static final List<String> REQUEST_HEADERS = Arrays.asList( "Content-Type", "Accept" );
public static final Producer<RESTDocsGenerator> PRODUCER = new Producer<RESTDocsGenerator>()
{
@Override
public RESTDocsGenerator create( GraphDefinition graph, String title, String documentation )
{
RESTDocsGenerator gen = RESTDocsGenerator.create( title );
gen.description(documentation);
return gen;
}
@Override
public void destroy( RESTDocsGenerator product, boolean successful )
{
// TODO: invoke some complete method here?
}
};
private int expectedResponseStatus = -1;
private MediaType expectedMediaType = MediaType.valueOf( "application/json; charset=UTF-8" );
private MediaType payloadMediaType = MediaType.APPLICATION_JSON_TYPE;
private final List<String> expectedHeaderFields = new ArrayList<>();
private String payload;
private final Map<String, String> addedRequestHeaders = new TreeMap<>( );
private boolean noDoc = false;
private boolean noGraph = false;
private int headingLevel = 3;
/**
* Creates a documented test case. Finish building it by using one of these:
* {@link #get(String)}, {@link #post(String)}, {@link #put(String)},
* {@link #delete(String)}, {@link #request(ClientRequest)}. To access the
* response, use {@link ResponseEntity#entity} to get the entity or
* {@link ResponseEntity#response} to get the rest of the response
* (excluding the entity).
*
* @param title title of the test
*/
public static RESTDocsGenerator create( final String title )
{
if ( title == null )
{
throw new IllegalArgumentException( "The title can not be null" );
}
return new RESTDocsGenerator( title );
}
private RESTDocsGenerator( String title )
{
super( title, "rest-api" );
}
/**
* Set the expected status of the response. The test will fail if the
* response has a different status. Defaults to HTTP 200 OK.
*
* @param expectedResponseStatus the expected response status
*/
public RESTDocsGenerator expectedStatus( final int expectedResponseStatus )
{
this.expectedResponseStatus = expectedResponseStatus;
return this;
}
/**
* Set the expected status of the response. The test will fail if the
* response has a different status. Defaults to HTTP 200 OK.
*
* @param expectedStatus the expected response status
*/
public RESTDocsGenerator expectedStatus( final ClientResponse.Status expectedStatus)
{
this.expectedResponseStatus = expectedStatus.getStatusCode();
return this;
}
/**
* Set the expected media type of the response. The test will fail if the
* response has a different media type. Defaults to application/json.
*
* @param expectedMediaType the expected media tyupe
*/
public RESTDocsGenerator expectedType( final MediaType expectedMediaType )
{
this.expectedMediaType = expectedMediaType;
return this;
}
/**
* The media type of the request payload. Defaults to application/json.
*
* @param payloadMediaType the media type to use
*/
public RESTDocsGenerator payloadType( final MediaType payloadMediaType )
{
this.payloadMediaType = payloadMediaType;
return this;
}
/**
* The additional headers for the request
*
* @param key header key
* @param value header value
*/
public RESTDocsGenerator withHeader( final String key, final String value )
{
this.addedRequestHeaders.put(key,value);
return this;
}
/**
* Set the payload of the request.
*
* @param payload the payload
*/
public RESTDocsGenerator payload( final String payload )
{
this.payload = payload;
return this;
}
public RESTDocsGenerator noDoc() {
this.noDoc = true;
return this;
}
public RESTDocsGenerator noGraph()
{
this.noGraph = true;
return this;
}
/**
* Set a custom heading level. Defaults to 3.
*
* @param headingLevel a value between 1 and 6 (inclusive)
*/
public RESTDocsGenerator docHeadingLevel( final int headingLevel )
{
if ( headingLevel < 1 || headingLevel > EQUAL_SIGNS.length() )
{
throw new IllegalArgumentException( "Heading level out of bounds: "
+ headingLevel );
}
this.headingLevel = headingLevel;
return this;
}
/**
* Add an expected response header. If the heading is missing in the
* response the test will fail. The header and its value are also included
* in the documentation.
*
* @param expectedHeaderField the expected header
*/
public RESTDocsGenerator expectedHeader( final String expectedHeaderField )
{
this.expectedHeaderFields.add( expectedHeaderField );
return this;
}
/**
* Send a request using your own request object.
*
* @param request the request to perform
*/
public ResponseEntity request( final ClientRequest request )
{
return retrieveResponse( title, description, request.getURI()
.toString(), expectedResponseStatus, expectedMediaType, expectedHeaderFields, request );
}
@Override
public RESTDocsGenerator description( String description )
{
return (RESTDocsGenerator) super.description( description );
}
/**
* Send a GET request.
*
* @param uri the URI to use.
*/
public ResponseEntity get( final String uri )
{
return retrieveResponseFromRequest( title, description, "GET", uri, expectedResponseStatus, expectedMediaType,
expectedHeaderFields );
}
/**
* Send a POST request.
*
* @param uri the URI to use.
*/
public ResponseEntity post( final String uri )
{
return retrieveResponseFromRequest( title, description, "POST", uri, payload, payloadMediaType,
expectedResponseStatus, expectedMediaType, expectedHeaderFields );
}
/**
* Send a PUT request.
*
* @param uri the URI to use.
*/
public ResponseEntity put( final String uri )
{
return retrieveResponseFromRequest( title, description, "PUT", uri, payload, payloadMediaType,
expectedResponseStatus, expectedMediaType, expectedHeaderFields );
}
/**
* Send a DELETE request.
*
* @param uri the URI to use.
*/
public ResponseEntity delete( final String uri )
{
return retrieveResponseFromRequest( title, description, "DELETE", uri, payload, payloadMediaType,
expectedResponseStatus, expectedMediaType, expectedHeaderFields );
}
/**
* Send a request with no payload.
*/
private ResponseEntity retrieveResponseFromRequest( final String title, final String description,
final String method, final String uri, final int responseCode, final MediaType accept,
final List<String> headerFields )
{
ClientRequest request;
try
{
request = withHeaders(REQUEST_BUILDER)
.accept(accept)
.build( new URI( uri ), method );
}
catch ( URISyntaxException e )
{
throw new RuntimeException( e );
}
return retrieveResponse( title, description, uri, responseCode, accept, headerFields, request );
}
/**
* Send a request with payload.
*/
private ResponseEntity retrieveResponseFromRequest( final String title, final String description,
final String method, final String uri, final String payload, final MediaType payloadType,
final int responseCode, final MediaType accept, final List<String> headerFields )
{
ClientRequest request;
try
{
if ( payload != null )
{
request = withHeaders(REQUEST_BUILDER)
.type(payloadType)
.accept(accept)
.entity(payload)
.build( new URI( uri ), method );
}
else
{
request = withHeaders(REQUEST_BUILDER).accept( accept )
.build(new URI(uri), method);
}
}
catch ( URISyntaxException e )
{
throw new RuntimeException( e );
}
return retrieveResponse( title, description, uri, responseCode, accept, headerFields, request );
}
private <T extends Builder> T withHeaders(T builder) {
for (Entry<String, String> entry : addedRequestHeaders.entrySet()) {
builder.header(entry.getKey(),entry.getValue());
}
return builder;
}
/**
* Send the request and create the documentation.
*/
private ResponseEntity retrieveResponse( final String title, final String description, final String uri,
final int responseCode, final MediaType type, final List<String> headerFields, final ClientRequest request )
{
DocumentationData data = new DocumentationData();
getRequestHeaders( data, request.getHeaders() );
if ( request.getEntity() != null )
{
data.setPayload( String.valueOf( request.getEntity() ) );
List<Object> contentTypes = request.getHeaders()
.get( "Content-Type" );
if ( contentTypes != null )
{
if ( contentTypes.size() != 1 )
{
throw new IllegalArgumentException(
"Request contains multiple content-types." );
}
Object contentType = contentTypes.get( 0 );
if ( contentType instanceof MediaType )
{
data.setPayloadType( (MediaType) contentType );
}
}
// data.setPayloadType( contentType );
}
Client client = new Client();
ClientResponse response = client.handle( request );
if ( response.hasEntity() && response.getStatus() != 204 )
{
data.setEntity( response.getEntity( String.class ) );
}
if ( response.getType() != null )
{
assertTrue( "wrong response type: "+ data.entity, response.getType().isCompatible( type ) );
}
for ( String headerField : headerFields )
{
assertNotNull( "wrong headers: "+ data.entity, response.getHeaders()
.get( headerField ) );
}
if ( noDoc )
{
data.setIgnore();
}
data.setTitle( title );
data.setDescription( description );
data.setMethod( request.getMethod() );
data.setUri( uri );
data.setStatus( responseCode );
assertEquals( "Wrong response status. response: " + data.entity, responseCode, response.getStatus() );
getResponseHeaders( data, response.getHeaders(), headerFields );
if ( graph == null )
{
document( data );
}
else
{
try ( Transaction transaction = graph.beginTx() )
{
document( data );
}
}
return new ResponseEntity( response, data.entity );
}
private void getResponseHeaders( final DocumentationData data, final MultivaluedMap<String, String> headers,
final List<String> additionalFilter )
{
data.setResponseHeaders( getHeaders( headers, RESPONSE_HEADERS, additionalFilter ) );
}
private void getRequestHeaders( final DocumentationData data, final MultivaluedMap<String, Object> headers )
{
data.setRequestHeaders( getHeaders( headers, REQUEST_HEADERS,
addedRequestHeaders.keySet() ) );
}
private <T> Map<String, String> getHeaders( final MultivaluedMap<String, T> headers, final List<String> filter,
final Collection<String> additionalFilter )
{
Map<String, String> filteredHeaders = new TreeMap<>();
for ( Entry<String, List<T>> header : headers.entrySet() )
{
String key = header.getKey();
if ( filter.contains( key ) || additionalFilter.contains( key ) )
{
String values = "";
for ( T value : header.getValue() )
{
if ( !values.isEmpty() )
{
values += ", ";
}
values += String.valueOf( value );
}
filteredHeaders.put( key, values );
}
}
return filteredHeaders;
}
/**
* Wraps a response, to give access to the response entity as well.
*/
public static class ResponseEntity
{
private final String entity;
private final JaxRsResponse response;
public ResponseEntity( ClientResponse response, String entity )
{
this.response = new JaxRsResponse(response,entity);
this.entity = entity;
}
/**
* The response entity as a String.
*/
public String entity()
{
return entity;
}
/**
* Note that the response object returned does not give access to the
* response entity.
*/
public JaxRsResponse response()
{
return response;
}
}
protected void document( final DocumentationData data )
{
if (data.ignore)
{
return;
}
String name = data.title.replace( " ", "-" ).toLowerCase();
String filename = name + ".asciidoc";
File dir = new File( new File( new File( "target" ), "docs" ), section );
data.description = replaceSnippets( data.description, dir, name );
try ( Writer fw = AsciiDocGenerator.getFW( dir, filename ) )
{
String longSection = section.replaceAll( "\\(|\\)", "" )+"-" + name.replaceAll( "\\(|\\)", "" );
if(longSection.indexOf( "/" )>0)
{
longSection = longSection.substring( longSection.indexOf( "/" )+1 );
}
line( fw, "[[" + longSection + "]]" );
//make first Character uppercase
String firstChar = data.title.substring( 0, 1 ).toUpperCase();
String heading = firstChar + data.title.substring( 1 );
line( fw, getAsciidocHeading( heading ) );
line( fw, "" );
if ( data.description != null && !data.description.isEmpty() )
{
line( fw, data.description );
line( fw, "" );
}
if ( !noGraph && graph != null )
{
fw.append( AsciiDocGenerator.dumpToSeparateFile( dir,
name + ".graph",
AsciidocHelper.createGraphVizWithNodeId( "Final Graph",
graph, title ) ) );
line(fw, "" );
}
line( fw, "_Example request_" );
line( fw, "" );
StringBuilder sb = new StringBuilder( 512 );
sb.append( "* *+" )
.append( data.method )
.append( "+* +" )
.append( data.uri )
.append( "+\n" );
if ( data.requestHeaders != null )
{
for ( Entry<String, String> header : data.requestHeaders.entrySet() )
{
sb.append( "* *+" )
.append( header.getKey() )
.append( ":+* +" )
.append( header.getValue() )
.append( "+\n" );
}
}
String prettifiedPayload = data.getPayload();
if ( prettifiedPayload != null )
{
writeEntity( sb, prettifiedPayload );
}
fw.append( AsciiDocGenerator.dumpToSeparateFile( dir, name
+ ".request",
sb.toString() ) );
sb = new StringBuilder( 2048 );
line( fw, "" );
line( fw, "_Example response_" );
line( fw, "" );
sb.append( "* *+" )
.append( data.status )
.append( ":+* +" )
.append( Response.Status.fromStatusCode( data.status ) )
.append( "+\n" );
if ( data.responseHeaders != null )
{
for ( Entry<String, String> header : data.responseHeaders.entrySet() )
{
sb.append( "* *+" )
.append( header.getKey() )
.append( ":+* +" )
.append( header.getValue() )
.append( "+\n" );
}
}
writeEntity( sb, data.getPrettifiedEntity() );
fw.append( AsciiDocGenerator.dumpToSeparateFile( dir,
name + ".response", sb.toString() ) );
line( fw, "" );
}
catch ( IOException e )
{
e.printStackTrace();
fail();
}
}
private String getAsciidocHeading( final String heading )
{
String equalSigns = EQUAL_SIGNS.substring( 0, headingLevel );
return equalSigns + ' ' + heading + ' ' + equalSigns;
}
public void writeEntity( final StringBuilder sb, final String entity )
{
if ( entity != null )
{
sb.append( "\n[source,javascript]\n" )
.append( "----\n" )
.append( entity )
.append( "\n----\n\n" );
}
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_RESTDocsGenerator.java
|
2,849
|
public class PrettyJSON extends JSONStringer
{
@Override
public String toString()
{
String json = super.toString();
return JSONPrettifier.parse( json );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_PrettyJSON.java
|
2,850
|
public class PathsDocIT extends AbstractRestFunctionalTestBase
{
/**
* The +shortestPath+ algorithm can find multiple paths between the same
* nodes, like in this example.
*/
@Test
@Graph( value = { "a to c", "a to d", "c to b", "d to e", "b to f", "c to f", "f to g", "d to g", "e to g",
"c to g" } )
@Documented
@Title( "Find all shortest paths" )
public void shouldBeAbleToFindAllShortestPaths() throws PropertyValueException
{
// Get all shortest paths
long a = nodeId( data.get(), "a" );
long g = nodeId( data.get(), "g" );
String response = gen()
.expectedStatus( Status.OK.getStatusCode() )
.payload( getAllShortestPathPayLoad( g ) )
.post( "http://localhost:7474/db/data/node/" + a + "/paths" )
.entity();
Collection<?> result = (Collection<?>) JsonHelper.jsonToSingleValue( response );
assertEquals( 2, result.size() );
for ( Object representation : result )
{
Map<?, ?> path = (Map<?, ?>) representation;
assertThatPathStartsWith( path, a );
assertThatPathEndsWith( path, g );
assertThatPathHasLength( path, 2 );
}
}
/**
* If no path algorithm is specified, a +shortestPath+ algorithm with a max
* depth of 1 will be chosen. In this example, the +max_depth+ is set to +3+
* in order to find the shortest path between a maximum of 3 linked nodes.
*/
@Title( "Find one of the shortest paths" )
@Test
@Graph( value = { "a to c", "a to d", "c to b", "d to e", "b to f", "c to f", "f to g", "d to g", "e to g",
"c to g" } )
@Documented
public void shouldBeAbleToFetchSingleShortestPath() throws JsonParseException
{
long a = nodeId( data.get(), "a" );
long g = nodeId( data.get(), "g" );
String response = gen()
.expectedStatus( Status.OK.getStatusCode() )
.payload( getAllShortestPathPayLoad( g ) )
.post( "http://localhost:7474/db/data/node/" + a + "/path" )
.entity();
// Get single shortest path
Map<?, ?> path = JsonHelper.jsonToMap( response );
assertThatPathStartsWith( path, a );
assertThatPathEndsWith( path, g );
assertThatPathHasLength( path, 2 );
}
private void assertThatPathStartsWith( final Map<?, ?> path, final long start )
{
assertTrue( "Path should start with " + start + "\nBut it was " + path, path.get( "start" )
.toString()
.endsWith( "/node/" + start ) );
}
private void assertThatPathEndsWith( final Map<?, ?> path, final long start )
{
assertTrue( "Path should end with " + start + "\nBut it was " + path, path.get( "end" )
.toString()
.endsWith( "/node/" + start ) );
}
private void assertThatPathHasLength( final Map<?, ?> path, final int length )
{
Object actual = path.get( "length" );
assertEquals( "Expected path to have a length of " + length + "\nBut it was " + actual, length, actual );
}
/**
* This example is running a Dijkstra algorithm over a graph with different
* cost properties on different relationships. Note that the request URI
* ends with +/path+ which means a single path is what we want here.
*/
@Test
@Graph( nodes = { @NODE( name = "a", setNameProperty = true ), @NODE( name = "b", setNameProperty = true ),
@NODE( name = "c", setNameProperty = true ), @NODE( name = "d", setNameProperty = true ),
@NODE( name = "e", setNameProperty = true ), @NODE( name = "f", setNameProperty = true ) }, relationships = {
@REL( start = "a", end = "b", type = "to", properties = { @PROP( key = "cost", value = "1.5", type = GraphDescription.PropType.DOUBLE ) } ),
@REL( start = "a", end = "c", type = "to", properties = { @PROP( key = "cost", value = "0.5", type = GraphDescription.PropType.DOUBLE ) } ),
@REL( start = "a", end = "f", type = "to", properties = { @PROP( key = "cost", value = "0.5", type = GraphDescription.PropType.DOUBLE ) } ),
@REL( start = "c", end = "d", type = "to", properties = { @PROP( key = "cost", value = "0.5", type = GraphDescription.PropType.DOUBLE ) } ),
@REL( start = "d", end = "e", type = "to", properties = { @PROP( key = "cost", value = "0.5", type = GraphDescription.PropType.DOUBLE ) } ),
@REL( start = "b", end = "e", type = "to", properties = { @PROP( key = "cost", value = "0.5", type = GraphDescription.PropType.DOUBLE ) } ),
@REL( start = "f", end = "e", type = "to", properties = { @PROP( key = "cost", value = "1.2", type = GraphDescription.PropType.DOUBLE ) } ) } )
@Title( "Execute a Dijkstra algorithm and get a single path" )
@Documented
public void shouldGetCorrectDijkstraPathWithWeights() throws Exception
{
// Get cheapest paths using Dijkstra
long a = nodeId( data.get(), "a" );
long e = nodeId( data.get(), "e" );
String response = gen().expectedStatus( Status.OK.getStatusCode() )
.payload( getAllPathsUsingDijkstraPayLoad( e, false ) )
.post( "http://localhost:7474/db/data/node/" + a + "/path" )
.entity();
//
Map<?, ?> path = JsonHelper.jsonToMap( response );
assertThatPathStartsWith( path, a );
assertThatPathEndsWith( path, e );
assertThatPathHasLength( path, 3 );
assertEquals( 1.5, path.get( "weight" ) );
}
/**
* This example is running a Dijkstra algorithm over a graph with different
* cost properties on different relationships. Note that the request URI
* ends with +/paths+ which means we want multiple paths returned, in case
* they exist.
*/
@Test
@Graph( nodes = { @NODE( name = "a", setNameProperty = true ), @NODE( name = "b", setNameProperty = true ),
@NODE( name = "c", setNameProperty = true ), @NODE( name = "d", setNameProperty = true ),
@NODE( name = "e", setNameProperty = true ), @NODE( name = "f", setNameProperty = true ) }, relationships = {
@REL( start = "a", end = "b", type = "to", properties = { @PROP( key = "cost", value = "1.5", type = GraphDescription.PropType.DOUBLE ) } ),
@REL( start = "a", end = "c", type = "to", properties = { @PROP( key = "cost", value = "0.5", type = GraphDescription.PropType.DOUBLE ) } ),
@REL( start = "a", end = "f", type = "to", properties = { @PROP( key = "cost", value = "0.5", type = GraphDescription.PropType.DOUBLE ) } ),
@REL( start = "c", end = "d", type = "to", properties = { @PROP( key = "cost", value = "0.5", type = GraphDescription.PropType.DOUBLE ) } ),
@REL( start = "d", end = "e", type = "to", properties = { @PROP( key = "cost", value = "0.5", type = GraphDescription.PropType.DOUBLE ) } ),
@REL( start = "b", end = "e", type = "to", properties = { @PROP( key = "cost", value = "0.5", type = GraphDescription.PropType.DOUBLE ) } ),
@REL( start = "f", end = "e", type = "to", properties = { @PROP( key = "cost", value = "1.0", type = GraphDescription.PropType.DOUBLE ) } ) } )
@Title( "Execute a Dijkstra algorithm and get multiple paths" )
@Documented
public void shouldGetCorrectDijkstraPathsWithWeights() throws Exception
{
// Get cheapest paths using Dijkstra
long a = nodeId( data.get(), "a" );
long e = nodeId( data.get(), "e" );
String response = gen().expectedStatus( Status.OK.getStatusCode() )
.payload( getAllPathsUsingDijkstraPayLoad( e, false ) )
.post( "http://localhost:7474/db/data/node/" + a + "/paths" )
.entity();
//
List<Map<String, Object>> list = JsonHelper.jsonToList( response );
assertEquals( 2, list.size() );
Map<String, Object> firstPath = list.get( 0 );
Map<String, Object> secondPath = list.get( 1 );
System.out.println( firstPath );
System.out.println( secondPath );
assertThatPathStartsWith( firstPath, a );
assertThatPathStartsWith( secondPath, a );
assertThatPathEndsWith( firstPath, e );
assertThatPathEndsWith( secondPath, e );
assertEquals( 1.5, firstPath.get( "weight" ) );
assertEquals( 1.5, secondPath.get( "weight" ) );
// 5 = 3 +2
assertEquals( 5, (Integer) firstPath.get( "length" ) + (Integer) secondPath.get( "length" ) );
assertThatPathHasLength( firstPath, 3 );
assertThatPathHasLength( secondPath, 2 );
}
/**
* The following is executing a Dijkstra search on a graph with equal
* weights on all relationships. This example is included to show the
* difference when the same graph structure is used, but the path weight is
* equal to the number of hops.
*/
@Test
@Graph( nodes = { @NODE( name = "a", setNameProperty = true ),
@NODE( name = "b", setNameProperty = true ), @NODE( name = "c", setNameProperty = true ),
@NODE( name = "d", setNameProperty = true ), @NODE( name = "e", setNameProperty = true ),
@NODE( name = "f", setNameProperty = true ) }, relationships = {
@REL( start = "a", end = "b", type = "to", properties = { @PROP( key = "cost", value = "1", type = GraphDescription.PropType.INTEGER ) } ),
@REL( start = "a", end = "c", type = "to", properties = { @PROP( key = "cost", value = "1", type = GraphDescription.PropType.INTEGER ) } ),
@REL( start = "a", end = "f", type = "to", properties = { @PROP( key = "cost", value = "1", type = GraphDescription.PropType.INTEGER ) } ),
@REL( start = "c", end = "d", type = "to", properties = { @PROP( key = "cost", value = "1", type = GraphDescription.PropType.INTEGER ) } ),
@REL( start = "d", end = "e", type = "to", properties = { @PROP( key = "cost", value = "1", type = GraphDescription.PropType.INTEGER ) } ),
@REL( start = "b", end = "e", type = "to", properties = { @PROP( key = "cost", value = "1", type = GraphDescription.PropType.INTEGER ) } ),
@REL( start = "f", end = "e", type = "to", properties = { @PROP( key = "cost", value = "1", type = GraphDescription.PropType.INTEGER ) } ) } )
@Title( "Execute a Dijkstra algorithm with equal weights on relationships" )
@Documented
public void shouldGetCorrectDijkstraPathsWithEqualWeightsWithDefaultCost() throws Exception
{
// Get cheapest path using Dijkstra
long a = nodeId( data.get(), "a" );
long e = nodeId( data.get(), "e" );
String response = gen()
.expectedStatus( Status.OK.getStatusCode() )
.payload( getAllPathsUsingDijkstraPayLoad( e, false ) )
.post( "http://localhost:7474/db/data/node/" + a + "/path" )
.entity();
//
Map<?, ?> path = JsonHelper.jsonToMap( response );
assertThatPathStartsWith( path, a );
assertThatPathEndsWith( path, e );
assertThatPathHasLength( path, 2 );
assertEquals( 2.0, path.get( "weight" ) );
}
@Test
@Graph( value = { "a to c", "a to d", "c to b", "d to e", "b to f", "c to f", "f to g", "d to g", "e to g",
"c to g" } )
public void shouldReturn404WhenFailingToFindASinglePath() throws JsonParseException
{
long a = nodeId( data.get(), "a" );
long g = nodeId( data.get(), "g" );
String noHitsJson = "{\"to\":\""
+ nodeUri( g )
+ "\", \"max_depth\":1, \"relationships\":{\"type\":\"dummy\", \"direction\":\"in\"}, \"algorithm\":\"shortestPath\"}";
String entity = gen()
.expectedStatus( Status.NOT_FOUND.getStatusCode() )
.payload( noHitsJson )
.post( "http://localhost:7474/db/data/node/" + a + "/path" )
.entity();
System.out.println( entity );
}
private long nodeId( final Map<String, Node> map, final String string )
{
return map.get( string )
.getId();
}
private String nodeUri( final long l )
{
return NODES + l;
}
private String getAllShortestPathPayLoad( final long to )
{
String json = "{\"to\":\""
+ nodeUri( to )
+ "\", \"max_depth\":3, \"relationships\":{\"type\":\"to\", \"direction\":\"out\"}, \"algorithm\":\"shortestPath\"}";
return json;
}
//
private String getAllPathsUsingDijkstraPayLoad( final long to, final boolean includeDefaultCost )
{
String json = "{\"to\":\"" + nodeUri( to ) + "\"" + ", \"cost_property\":\"cost\""
+ ( includeDefaultCost ? ", \"default_cost\":1" : "" )
+ ", \"relationships\":{\"type\":\"to\", \"direction\":\"out\"}, \"algorithm\":\"dijkstra\"}";
return json;
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_PathsDocIT.java
|
2,851
|
public class ManageNodeDocIT extends AbstractRestFunctionalTestBase
{
private static final long NON_EXISTENT_NODE_ID = 999999;
private static String NODE_URI_PATTERN = "^.*/node/[0-9]+$";
private static FunctionalTestHelper functionalTestHelper;
private static GraphDbHelper helper;
@BeforeClass
public static void setupServer() throws IOException
{
functionalTestHelper = new FunctionalTestHelper( server() );
helper = functionalTestHelper.getGraphDbHelper();
}
@Before
public void cleanTheDatabase()
{
cleanDatabase();
}
@Test
public void create_node() throws Exception
{
JaxRsResponse response = gen.get()
.expectedStatus( 201 )
.expectedHeader( "Location" )
.post( functionalTestHelper.nodeUri() )
.response();
assertTrue( response.getLocation()
.toString()
.matches( NODE_URI_PATTERN ) );
}
@Test
public void create_node_with_properties() throws Exception
{
JaxRsResponse response = gen.get()
.payload( "{\"foo\" : \"bar\"}" )
.expectedStatus( 201 )
.expectedHeader( "Location" )
.expectedHeader( "Content-Length" )
.post( functionalTestHelper.nodeUri() )
.response();
assertTrue( response.getLocation()
.toString()
.matches( NODE_URI_PATTERN ) );
checkGeneratedFiles();
}
private void checkGeneratedFiles()
{
String requestDocs, responseDocs, graphDocs;
try
{
requestDocs = TestJavaTestDocsGenerator.readFileAsString( new File(
"target/docs/dev/rest-api/includes/create-node-with-properties.request.asciidoc" ) );
responseDocs = TestJavaTestDocsGenerator.readFileAsString( new File(
"target/docs/dev/rest-api/includes/create-node-with-properties.response.asciidoc" ) );
graphDocs = TestJavaTestDocsGenerator.readFileAsString( new File(
"target/docs/dev/rest-api/includes/create-node-with-properties.graph.asciidoc" ) );
}
catch ( IOException ioe )
{
throw new RuntimeException(
"Error reading generated documentation file: ", ioe );
}
for ( String s : new String[] { "POST", "Accept", "application/json",
"Content-Type", "{", "foo", "bar", "}" } )
{
assertThat( requestDocs, containsString( s ) );
}
for ( String s : new String[] { "201", "Created", "Content-Length",
"Content-Type", "Location", "{", "foo", "bar", "}" } )
{
assertThat( responseDocs, containsString( s ) );
}
for ( String s : new String[] { "foo", "bar" } )
{
assertThat( graphDocs, containsString( s ) );
}
}
@Test
public void create_node_with_array_properties() throws Exception
{
String response = gen.get()
.payload( "{\"foo\" : [1,2,3]}" )
.expectedStatus( 201 )
.expectedHeader( "Location" )
.expectedHeader( "Content-Length" )
.post( functionalTestHelper.nodeUri() )
.response().getEntity();
assertThat( response, containsString( "[ 1, 2, 3 ]" ) );
}
/**
* Property values can not be null.
*
* This example shows the response you get when trying to set a property to
* +null+.
*/
@Documented
@Test
public void shouldGet400WhenSupplyingNullValueForAProperty() throws Exception
{
gen.get()
.noGraph()
.payload( "{\"foo\":null}" )
.expectedStatus( 400 )
.post( functionalTestHelper.nodeUri() );
}
@Test
public void shouldGet400WhenCreatingNodeMalformedProperties() throws Exception
{
JaxRsResponse response = sendCreateRequestToServer("this:::isNot::JSON}");
assertEquals( 400, response.getStatus() );
}
@Test
public void shouldGet400WhenCreatingNodeUnsupportedNestedPropertyValues() throws Exception
{
JaxRsResponse response = sendCreateRequestToServer("{\"foo\" : {\"bar\" : \"baz\"}}");
assertEquals( 400, response.getStatus() );
}
private JaxRsResponse sendCreateRequestToServer(final String json)
{
return RestRequest.req().post( functionalTestHelper.dataUri() + "node/" , json );
}
private JaxRsResponse sendCreateRequestToServer()
{
return RestRequest.req().post( functionalTestHelper.dataUri() + "node/" , null, MediaType.APPLICATION_JSON_TYPE );
}
@Test
public void shouldGetValidLocationHeaderWhenCreatingNode() throws Exception
{
JaxRsResponse response = sendCreateRequestToServer();
assertNotNull( response.getLocation() );
assertTrue( response.getLocation()
.toString()
.startsWith( functionalTestHelper.dataUri() + "node/" ) );
}
@Test
public void shouldGetASingleContentLengthHeaderWhenCreatingANode()
{
JaxRsResponse response = sendCreateRequestToServer();
List<String> contentLentgthHeaders = response.getHeaders()
.get( "Content-Length" );
assertNotNull( contentLentgthHeaders );
assertEquals( 1, contentLentgthHeaders.size() );
}
@Test
public void shouldBeJSONContentTypeOnResponse()
{
JaxRsResponse response = sendCreateRequestToServer();
assertThat( response.getType().toString(), containsString( MediaType.APPLICATION_JSON ) );
}
@Test
public void shouldGetValidNodeRepresentationWhenCreatingNode() throws Exception
{
JaxRsResponse response = sendCreateRequestToServer();
String entity = response.getEntity();
Map<String, Object> map = JsonHelper.jsonToMap( entity );
assertNotNull( map );
assertTrue( map.containsKey( "self" ) );
}
/**
* Delete node.
*/
@Documented
@Test
public void shouldRespondWith204WhenNodeDeleted() throws Exception
{
gen.get()
.expectedStatus( 204 )
.delete( functionalTestHelper.dataUri() + "node/" + helper.createNode() );
}
@Test
public void shouldRespondWith404AndSensibleEntityBodyWhenNodeToBeDeletedCannotBeFound() throws Exception
{
JaxRsResponse response = sendDeleteRequestToServer(NON_EXISTENT_NODE_ID);
assertEquals( 404, response.getStatus() );
Map<String, Object> jsonMap = JsonHelper.jsonToMap( response.getEntity() );
assertThat( jsonMap, hasKey( "message" ) );
assertNotNull( jsonMap.get( "message" ) );
}
/**
* Nodes with relationships cannot be deleted.
*
* The relationships on a node has to be deleted before the node can be
* deleted.
*/
@Documented
@Test
public void shouldRespondWith409AndSensibleEntityBodyWhenNodeCannotBeDeleted() throws Exception
{
long id = helper.createNode();
helper.createRelationship( "LOVES", id, helper.createNode() );
JaxRsResponse response = sendDeleteRequestToServer(id);
assertEquals( 409, response.getStatus() );
Map<String, Object> jsonMap = JsonHelper.jsonToMap( response.getEntity() );
assertThat( jsonMap, hasKey( "message" ) );
assertNotNull( jsonMap.get( "message" ) );
gen.get()
.expectedStatus( 409 )
.delete( functionalTestHelper.dataUri() + "node/" + id );
}
@Test
public void shouldRespondWith400IfInvalidJsonSentAsNodePropertiesDuringNodeCreation() throws URISyntaxException
{
String mangledJsonArray = "{\"myprop\":[1,2,\"three\"]}";
JaxRsResponse response = sendCreateRequestToServer(mangledJsonArray);
assertEquals( 400, response.getStatus() );
assertEquals( "text/plain", response.getType()
.toString() );
assertThat( response.getEntity(), containsString( mangledJsonArray ) );
}
@Test
public void shouldRespondWith400IfInvalidJsonSentAsNodeProperty() throws URISyntaxException {
URI nodeLocation = sendCreateRequestToServer().getLocation();
String mangledJsonArray = "[1,2,\"three\"]";
JaxRsResponse response = RestRequest.req().put(nodeLocation.toString() + "/properties/myprop", mangledJsonArray);
assertEquals(400, response.getStatus());
assertEquals("text/plain", response.getType()
.toString());
assertThat( response.getEntity(), containsString(mangledJsonArray));
response.close();
}
@Test
public void shouldRespondWith400IfInvalidJsonSentAsNodeProperties() throws URISyntaxException {
URI nodeLocation = sendCreateRequestToServer().getLocation();
String mangledJsonProperties = "{\"a\":\"b\", \"c\":[1,2,\"three\"]}";
JaxRsResponse response = RestRequest.req().put(nodeLocation.toString() + "/properties", mangledJsonProperties);
assertEquals(400, response.getStatus());
assertEquals("text/plain", response.getType()
.toString());
assertThat( response.getEntity(), containsString(mangledJsonProperties));
response.close();
}
private JaxRsResponse sendDeleteRequestToServer(final long id) throws Exception
{
return RestRequest.req().delete(functionalTestHelper.dataUri() + "node/" + id);
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_ManageNodeDocIT.java
|
2,852
|
public class ListPropertyKeysDocIT extends AbstractRestFunctionalTestBase
{
/**
* List all property keys.
*/
@Test
@Documented
@GraphDescription.Graph( nodes = {
@GraphDescription.NODE( name = "a", setNameProperty = true ),
@GraphDescription.NODE( name = "b", setNameProperty = true ),
@GraphDescription.NODE( name = "c", setNameProperty = true )
} )
public void list_all_property_keys_ever_used() throws JsonParseException
{
data.get();
String uri = getPropertyKeysUri();
String body = gen.get()
.noGraph()
.expectedStatus( 200 )
.get( uri )
.entity();
Set<?> parsed = asSet((List<?>) readJson( body ));
assertTrue( parsed.contains( "name" ) );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_ListPropertyKeysDocIT.java
|
2,853
|
{
@Override
public T apply( Object from )
{
Map<?, ?> node = (Map<?, ?>) from;
Map<?, ?> data = (Map<?, ?>) node.get( "data" );
return propertyType.cast( data.get( propertyKey ) );
}
};
| false
|
community_server_src_test_java_org_neo4j_server_rest_LabelsDocIT.java
|
2,854
|
public class LabelsDocIT extends AbstractRestFunctionalTestBase
{
/**
* Adding a label to a node.
*/
@Documented
@Test
@GraphDescription.Graph( nodes = { @NODE( name = "Clint Eastwood", setNameProperty = true ) } )
public void adding_a_label_to_a_node() throws PropertyValueException
{
Map<String,Node> nodes = data.get();
String nodeUri = getNodeUri( nodes.get( "Clint Eastwood" ) );
gen.get()
.expectedStatus( 204 )
.payload( createJsonFrom( "Person" ) )
.post( nodeUri + "/labels" );
}
/**
* Adding multiple labels to a node.
*/
@Documented
@Test
@GraphDescription.Graph( nodes = { @NODE( name = "Clint Eastwood", setNameProperty = true ) } )
public void adding_multiple_labels_to_a_node() throws PropertyValueException
{
Map<String,Node> nodes = data.get();
String nodeUri = getNodeUri( nodes.get( "Clint Eastwood" ) );
gen.get()
.expectedStatus( 204 )
.payload( createJsonFrom( new String[]{"Person", "Actor"} ) )
.post( nodeUri + "/labels" );
// Then
assertThat( nodes.get( "Clint Eastwood" ), inTx( graphdb(), hasLabels( "Person", "Actor" ) ) );
}
/**
* Adding a label with an invalid name.
*
* Labels with empty names are not allowed, however, all other valid strings are accepted as label names.
* Adding an invalid label to a node will lead to a HTTP 400 response.
*/
@Documented
@Test
@GraphDescription.Graph( nodes = { @NODE( name = "Clint Eastwood", setNameProperty = true ) } )
public void adding_an_invalid_label_to_a_node() throws PropertyValueException
{
Map<String,Node> nodes = data.get();
String nodeUri = getNodeUri( nodes.get( "Clint Eastwood" ) );
gen.get()
.expectedStatus( 400 )
.payload( createJsonFrom( "" ) )
.post( nodeUri + "/labels" );
}
/**
* Replacing labels on a node.
*
* This removes any labels currently on a node, and replaces them with the labels passed in as the
* request body.
*/
@Documented
@Test
@GraphDescription.Graph( nodes = { @NODE( name = "Clint Eastwood", setNameProperty = true,
labels = { @LABEL( "Person" ) }) } )
public void replacing_labels_on_a_node() throws PropertyValueException
{
Map<String,Node> nodes = data.get();
String nodeUri = getNodeUri( nodes.get( "Clint Eastwood" ) );
// When
gen.get()
.expectedStatus( 204 )
.payload( createJsonFrom( new String[]{"Actor", "Director"}) )
.put( nodeUri + "/labels" );
// Then
assertThat( nodes.get( "Clint Eastwood" ), inTx(graphdb(), hasLabels("Actor", "Director")) );
}
/**
* Listing labels for a node.
*/
@Documented
@Test
@GraphDescription.Graph( nodes = { @NODE( name = "Clint Eastwood", labels = { @LABEL( "Actor" ), @LABEL( "Director" ) }, setNameProperty = true ) } )
public void listing_node_labels() throws PropertyValueException
{
Map<String, Node> nodes = data.get();
String nodeUri = getNodeUri( nodes.get( "Clint Eastwood" ) );
String body = gen.get()
.expectedStatus( 200 )
.get( nodeUri + "/labels" )
.entity();
@SuppressWarnings("unchecked")
List<String> labels = (List<String>) readJson( body );
assertEquals( asSet( "Actor", "Director" ), asSet( labels ) );
}
/**
* Removing a label from a node.
*/
@Documented
@Test
@GraphDescription.Graph( nodes = { @NODE( name = "Clint Eastwood", setNameProperty = true, labels = { @LABEL( "Person" ) } ) } )
public void removing_a_label_from_a_node() throws PropertyValueException
{
Map<String,Node> nodes = data.get();
Node node = nodes.get( "Clint Eastwood" );
String nodeUri = getNodeUri( node );
String labelName = "Person";
gen.get()
.expectedStatus( 204 )
.delete( nodeUri + "/labels/" + labelName );
assertThat( node, inTx( graphdb(), not( hasLabel( label( labelName ) ) ) ) );
}
/**
* Removing a non-existent label from a node.
*/
@Documented
@Test
@GraphDescription.Graph( nodes = { @NODE( name = "Clint Eastwood", setNameProperty = true ) } )
public void removing_a_non_existent_label_from_a_node() throws PropertyValueException
{
Map<String,Node> nodes = data.get();
Node node = nodes.get( "Clint Eastwood" );
String nodeUri = getNodeUri( node );
String labelName = "Person";
gen.get()
.expectedStatus( 204 )
.delete( nodeUri + "/labels/" + labelName );
assertThat( node, inTx( graphdb(), not( hasLabel( label( labelName ) ) ) ) );
}
/**
* Get all nodes with a label.
*/
@Documented
@Test
@GraphDescription.Graph( nodes = {
@NODE( name = "Clint Eastwood", setNameProperty = true, labels = { @LABEL( "Actor" ), @LABEL( "Director" ) } ),
@NODE( name = "Donald Sutherland", setNameProperty = true, labels = { @LABEL( "Actor" ) } ),
@NODE( name = "Steven Spielberg", setNameProperty = true, labels = { @LABEL( "Director" ) } )
} )
public void get_all_nodes_with_label() throws JsonParseException
{
data.get();
String uri = getNodesWithLabelUri( "Actor" );
String body = gen.get()
.expectedStatus( 200 )
.get( uri )
.entity();
List<?> parsed = (List<?>) readJson( body );
assertEquals( asSet( "Clint Eastwood", "Donald Sutherland" ), asSet( map( getProperty( "name", String.class ), parsed ) ) );
}
/**
* Get nodes by label and property.
*
* You can retrieve all nodes with a given label and property by passing one property as a query parameter.
* Notice that the property value is JSON-encoded and then URL-encoded.
*
* If there is an index available on the label/property combination you send, that index will be used. If no
* index is available, all nodes with the given label will be filtered through to find matching nodes.
*
* Currently, it is not possible to search using multiple properties.
*/
@Test
@Documented
@GraphDescription.Graph( nodes = {
@NODE( name = "Donald Sutherland", labels={ @LABEL( "Person" )} ),
@NODE( name = "Clint Eastwood", labels={ @LABEL( "Person" )}, properties = { @PROP( key = "name", value = "Clint Eastwood" )}),
@NODE( name = "Steven Spielberg", labels={ @LABEL( "Person" )}, properties = { @PROP( key = "name", value = "Steven Spielberg" )})})
public void get_nodes_with_label_and_property() throws PropertyValueException, UnsupportedEncodingException
{
data.get();
String labelName = "Person";
String result = gen.get()
.expectedStatus( 200 )
.get( getNodesWithLabelAndPropertyUri( labelName, "name", "Clint Eastwood" ) )
.entity();
List<?> parsed = (List<?>) readJson( result );
assertEquals( asSet( "Clint Eastwood" ), asSet( map( getProperty( "name", String.class ), parsed ) ) );
}
/**
* Get nodes by label and array property.
*/
@Test
@GraphDescription.Graph( nodes = {
@NODE(name = "Donald Sutherland", labels = {@LABEL("Person")}),
@NODE(name = "Clint Eastwood", labels = {@LABEL("Person")}, properties =
{@PROP(key = "names", value = "Clint,Eastwood", type = ARRAY, componentType = STRING)}),
@NODE(name = "Steven Spielberg", labels = {@LABEL("Person")}, properties =
{@PROP(key = "names", value = "Steven,Spielberg", type = ARRAY, componentType = STRING)})})
public void get_nodes_with_label_and_array_property() throws PropertyValueException, UnsupportedEncodingException
{
data.get();
String labelName = "Person";
String uri = getNodesWithLabelAndPropertyUri( labelName, "names", new String[] { "Clint", "Eastwood" } );
String result = gen.get()
.expectedStatus( 200 )
.get( uri )
.entity();
List<?> parsed = (List<?>) readJson( result );
assertEquals( 1, parsed.size() );
//noinspection AssertEqualsBetweenInconvertibleTypes
assertEquals( asSet( asList( asList( "Clint", "Eastwood" ) ) ),
asSet( map( getProperty( "names", List.class ), parsed ) ) );
}
/**
* List all labels.
*/
@Test
@Documented
@GraphDescription.Graph( nodes = {
@NODE( name = "Clint Eastwood", setNameProperty = true, labels = { @LABEL( "Person" ), @LABEL( "Actor" ), @LABEL( "Director" ) } ),
@NODE( name = "Donald Sutherland", setNameProperty = true, labels = { @LABEL( "Person" ), @LABEL( "Actor" ) } ),
@NODE( name = "Steven Spielberg", setNameProperty = true, labels = { @LABEL( "Person" ), @LABEL( "Director" ) } )
} )
public void list_all_labels() throws JsonParseException
{
data.get();
String uri = getLabelsUri();
String body = gen.get()
.expectedStatus( 200 )
.get( uri )
.entity();
Set<?> parsed = asSet((List<?>) readJson( body ));
assertTrue( parsed.contains( "Person" ) );
assertTrue( parsed.contains( "Actor" ) );
assertTrue( parsed.contains( "Director" ) );
}
private <T> Function<Object, T> getProperty( final String propertyKey, final Class<T> propertyType )
{
return new Function<Object, T>()
{
@Override
public T apply( Object from )
{
Map<?, ?> node = (Map<?, ?>) from;
Map<?, ?> data = (Map<?, ?>) node.get( "data" );
return propertyType.cast( data.get( propertyKey ) );
}
};
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_LabelsDocIT.java
|
2,855
|
public class SetRelationshipPropertiesDocIT extends AbstractRestFunctionalTestBase
{
private URI propertiesUri;
private URI badUri;
private static FunctionalTestHelper functionalTestHelper;
@BeforeClass
public static void setupServer() throws IOException
{
functionalTestHelper = new FunctionalTestHelper( server() );
}
@Before
public void setupTheDatabase() throws Exception
{
cleanDatabase();
long relationshipId = new GraphDbHelper( server().getDatabase() ).createRelationship( "KNOWS" );
propertiesUri = new URI( functionalTestHelper.relationshipPropertiesUri( relationshipId ) );
badUri = new URI( functionalTestHelper.relationshipPropertiesUri( relationshipId + 1 * 99999 ) );
}
/**
* Update relationship properties.
*/
@Documented
@Test
@Graph
public void shouldReturn204WhenPropertiesAreUpdated() throws JsonParseException
{
data.get();
Map<String, Object> map = new HashMap<String, Object>();
map.put( "jim", "tobias" );
gen.get()
.payload( JsonHelper.createJsonFrom( map ) )
.expectedStatus( 204 )
.put( propertiesUri.toString() );
JaxRsResponse response = updatePropertiesOnServer(map);
assertEquals( 204, response.getStatus() );
response.close();
}
@Test
public void shouldReturn400WhenSendinIncompatibleJsonProperties() throws JsonParseException
{
Map<String, Object> map = new HashMap<String, Object>();
map.put( "jim", new HashMap<String, Object>() );
JaxRsResponse response = updatePropertiesOnServer(map);
assertEquals( 400, response.getStatus() );
response.close();
}
@Test
public void shouldReturn400WhenSendingCorruptJsonProperties() {
JaxRsResponse response = RestRequest.req().put(propertiesUri.toString(), "this:::Is::notJSON}");
assertEquals(400, response.getStatus());
response.close();
}
@Test
public void shouldReturn404WhenPropertiesSentToANodeWhichDoesNotExist() throws JsonParseException {
Map<String, Object> map = new HashMap<String, Object>();
map.put("jim", "tobias");
JaxRsResponse response = RestRequest.req().put(badUri.toString(), JsonHelper.createJsonFrom(map));
assertEquals(404, response.getStatus());
response.close();
}
private JaxRsResponse updatePropertiesOnServer(final Map<String, Object> map) throws JsonParseException
{
return RestRequest.req().put(propertiesUri.toString(), JsonHelper.createJsonFrom(map));
}
private String getPropertyUri(final String key) throws Exception
{
return propertiesUri.toString() + "/" + key ;
}
@Test
public void shouldReturn204WhenPropertyIsSet() throws Exception
{
JaxRsResponse response = setPropertyOnServer("foo", "bar");
assertEquals( 204, response.getStatus() );
response.close();
}
@Test
public void shouldReturn400WhenSendinIncompatibleJsonProperty() throws Exception
{
JaxRsResponse response = setPropertyOnServer("jim", new HashMap<String, Object>());
assertEquals( 400, response.getStatus() );
response.close();
}
@Test
public void shouldReturn400WhenSendingCorruptJsonProperty() throws Exception {
JaxRsResponse response = RestRequest.req().put(getPropertyUri("foo"), "this:::Is::notJSON}");
assertEquals(400, response.getStatus());
response.close();
}
@Test
public void shouldReturn404WhenPropertySentToANodeWhichDoesNotExist() throws Exception {
JaxRsResponse response = RestRequest.req().put(badUri.toString() + "/foo", JsonHelper.createJsonFrom("bar"));
assertEquals(404, response.getStatus());
response.close();
}
private JaxRsResponse setPropertyOnServer(final String key, final Object value) throws Exception {
return RestRequest.req().put(getPropertyUri(key), JsonHelper.createJsonFrom(value));
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_SetRelationshipPropertiesDocIT.java
|
2,856
|
public class BatchOperationResults
{
private static final String CLOSING_BRACKET = "]";
private static final String OPENING_BRACKET = "[";
private static final String OPENING_CURLY = "{";
private static final String CLOSING_CURLY = "}";
private static final String COMMA = ",";
private StringWriter results = new StringWriter();
private boolean firstResult = true;
private Map<Integer, String> locations = new HashMap<Integer, String>();
public BatchOperationResults() {
results.append( OPENING_BRACKET );
}
public void addOperationResult( String from, Integer id, String body, String location )
{
if(firstResult)
firstResult = false;
else
results.append(',');
results.append( OPENING_CURLY );
if ( id != null )
{
results.append( "\"id\":" )
.append( id.toString() )
.append( COMMA );
}
if ( location != null )
{
locations.put( id, location );
results.append( "\"location\":" )
.append( JsonHelper.createJsonFrom( location ) )
.append( COMMA );
}
if ( body != null && body.length() != 0 )
{
results.append( "\"body\":" )
.append( body )
.append( COMMA );
}
results.append( "\"from\":" )
.append( JsonHelper.createJsonFrom( from ) );
results.append( CLOSING_CURLY );
}
public Map<Integer, String> getLocations()
{
return locations;
}
public String toJSON()
{
results.append( CLOSING_BRACKET );
return results.toString();
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_batch_BatchOperationResults.java
|
2,857
|
@SuppressWarnings( "serial" )
public class JsonBuildRuntimeException extends RuntimeException
{
public JsonBuildRuntimeException( String message, Throwable cause )
{
super( message, cause );
}
public JsonBuildRuntimeException( String message )
{
super( message );
}
public JsonBuildRuntimeException( Throwable cause )
{
super( cause );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_domain_JsonBuildRuntimeException.java
|
2,858
|
public abstract class BatchOperations
{
protected static final String ID_KEY = "id";
protected static final String METHOD_KEY = "method";
protected static final String BODY_KEY = "body";
protected static final String TO_KEY = "to";
protected static final JsonFactory jsonFactory = new JsonFactory();
protected final WebServer webServer;
protected final ObjectMapper mapper;
public BatchOperations( WebServer webServer )
{
this.webServer = webServer;
mapper = new ObjectMapper();
}
protected void addHeaders( final InternalJettyServletRequest res,
final HttpHeaders httpHeaders )
{
for (Map.Entry<String, List<String>> header : httpHeaders
.getRequestHeaders().entrySet())
{
final String key = header.getKey();
final List<String> value = header.getValue();
if (value == null)
{
continue;
}
if (value.size() != 1)
{
throw new IllegalArgumentException(
"expecting one value per header");
}
if ( !key.equals( "Accept" ) && !key.equals( "Content-Type" ) )
{
res.addHeader(key, value.get(0));
}
}
// Make sure they are there and always json
// Taking advantage of Map semantics here
res.addHeader("Accept", "application/json");
res.addHeader("Content-Type", "application/json");
}
protected URI calculateTargetUri( UriInfo serverUriInfo, String requestedPath )
{
URI baseUri = serverUriInfo.getBaseUri();
if (requestedPath.startsWith(baseUri.toString()))
{
requestedPath = requestedPath
.substring( baseUri.toString().length() );
}
if (!requestedPath.startsWith("/"))
{
requestedPath = "/" + requestedPath;
}
return baseUri.resolve("." + requestedPath);
}
private final static Pattern PLACHOLDER_PATTERN=Pattern.compile("\\{(\\d+)\\}");
protected String replaceLocationPlaceholders( String str,
Map<Integer, String> locations )
{
if (!str.contains( "{" ))
{
return str;
}
Matcher matcher = PLACHOLDER_PATTERN.matcher(str);
StringBuffer sb=new StringBuffer();
while (matcher.find()) {
String id = matcher.group(1);
String replacement = locations.get(Integer.valueOf(id));
if (replacement!=null)
{
matcher.appendReplacement(sb,replacement);
}
else
{
matcher.appendReplacement(sb,matcher.group());
}
}
matcher.appendTail(sb);
return sb.toString();
}
protected boolean is2XXStatusCode( int statusCode )
{
return statusCode >= 200 && statusCode < 300;
}
protected void parseAndPerform( UriInfo uriInfo, HttpHeaders httpHeaders, InputStream body, Map<Integer, String> locations ) throws IOException, ServletException
{
JsonParser jp = jsonFactory.createJsonParser(body);
JsonToken token;
while ((token = jp.nextToken()) != null)
{
if (token == JsonToken.START_OBJECT)
{
String jobMethod="", jobPath="", jobBody="";
Integer jobId = null;
while ((token = jp.nextToken()) != JsonToken.END_OBJECT && token != null )
{
String field = jp.getText();
jp.nextToken();
switch ( field )
{
case METHOD_KEY:
jobMethod = jp.getText().toUpperCase();
break;
case TO_KEY:
jobPath = jp.getText();
break;
case ID_KEY:
jobId = jp.getIntValue();
break;
case BODY_KEY:
jobBody = readBody( jp );
break;
}
}
// Read one job description. Execute it.
performRequest( uriInfo, jobMethod, jobPath, jobBody,
jobId, httpHeaders, locations );
}
}
}
private String readBody( JsonParser jp ) throws IOException
{
JsonNode node = mapper.readTree( jp );
StringWriter out = new StringWriter();
JsonGenerator gen = jsonFactory
.createJsonGenerator(out);
mapper.writeTree( gen, node );
gen.flush();
gen.close();
return out.toString();
}
protected void performRequest( UriInfo uriInfo, String method, String path, String body, Integer id, HttpHeaders httpHeaders, Map<Integer, String> locations ) throws IOException, ServletException
{
path = replaceLocationPlaceholders(path, locations);
body = replaceLocationPlaceholders(body, locations);
URI targetUri = calculateTargetUri(uriInfo, path);
InternalJettyServletResponse res = new InternalJettyServletResponse();
InternalJettyServletRequest req = new InternalJettyServletRequest( method, targetUri.toString(), body, res);
req.setScheme( targetUri.getScheme() );
addHeaders( req, httpHeaders );
invoke( method, path, body, id, targetUri, req, res );
}
protected abstract void invoke( String method, String path, String body, Integer id, URI targetUri, InternalJettyServletRequest req, InternalJettyServletResponse res ) throws IOException, ServletException;
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_batch_BatchOperations.java
|
2,859
|
public class HtmlHelper
{
private final static String STYLE_LOCATION = "http://resthtml.neo4j.org/style/";
private final static String HTML_JAVASCRIPT_LOCATION = "/webadmin/htmlbrowse.js";
public static String from( final Object object, final ObjectType objectType )
{
StringBuilder builder = start( objectType, null );
append( builder, object, objectType );
return end( builder );
}
public static StringBuilder start( final ObjectType objectType, final String additionalCodeInHead )
{
return start( objectType.getCaption(), additionalCodeInHead );
}
public static StringBuilder start( final String title, final String additionalCodeInHead )
{
StringBuilder builder = new StringBuilder();
builder.append( "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n" );
builder.append( "<html><head><title>" + title + "</title>" );
if ( additionalCodeInHead != null )
{
builder.append( additionalCodeInHead );
}
builder.append( "<meta content=\"text/html; charset=utf-8\" http-equiv=\"Content-Type\">\n" + "<link href='"
+ STYLE_LOCATION + "rest.css' rel='stylesheet' type='text/css'>\n"
+ "<script type='text/javascript' src='" + HTML_JAVASCRIPT_LOCATION + "'></script>\n"
+ "</head>\n<body onload='javascript:neo4jHtmlBrowse.start();' id='" + title.toLowerCase()
+ "'>\n" + "<div id='content'>" + "<div id='header'>"
+ "<h1><a title='Neo4j REST interface' href='/'><span>Neo4j REST interface</span></a></h1>"
+ "</div>" + "\n<div id='page-body'>\n" );
return builder;
}
public static String end( final StringBuilder builder )
{
builder.append( "<div class='break'> </div>" + "</div></div></body></html>" );
return builder.toString();
}
public static void appendMessage( final StringBuilder builder, final String message )
{
builder.append( "<p class=\"message\">" + message + "</p>" );
}
public static void append( final StringBuilder builder, final Object object, final ObjectType objectType )
{
if ( object instanceof Collection )
{
builder.append( "<ul>\n" );
for ( Object item : (Collection<?>) object )
{
builder.append( "<li>" );
append( builder, item, objectType );
builder.append( "</li>\n" );
}
builder.append( "</ul>\n" );
}
else if ( object instanceof Map )
{
Map<?, ?> map = (Map<?, ?>) object;
String htmlClass = objectType.getHtmlClass();
String caption = objectType.getCaption();
if ( !map.isEmpty() )
{
boolean isNodeOrRelationship = ObjectType.NODE.equals( objectType )
|| ObjectType.RELATIONSHIP.equals( objectType );
if ( isNodeOrRelationship )
{
builder.append( "<h2>" + caption + "</h2>\n" );
append( builder, map.get( "data" ), ObjectType.PROPERTIES );
htmlClass = "meta";
caption += " info";
}
if ( ObjectType.NODE.equals( objectType ) && map.size() == 1 )
{
// there's only properties, so we're finished here
return;
}
builder.append( "<table class=\"" + htmlClass + "\"><caption>" );
builder.append( caption );
builder.append( "</caption>\n" );
boolean odd = true;
for ( Map.Entry<?, ?> entry : map.entrySet() )
{
if ( isNodeOrRelationship && "data".equals( entry.getKey() ) )
{
continue;
}
builder.append( "<tr" + ( odd ? " class='odd'" : "" ) + ">" );
odd = !odd;
builder.append( "<th>" + entry.getKey() + "</th><td>" );
// TODO We always assume that an inner map is for
// properties, correct?
append( builder, entry.getValue(), ObjectType.PROPERTIES );
builder.append( "</td></tr>\n" );
}
builder.append( "</table>\n" );
}
else
{
builder.append( "<table class=\"" + htmlClass + "\"><caption>" );
builder.append( caption );
builder.append( "</caption>" );
builder.append( "<tr><td></td></tr>" );
builder.append( "</table>" );
}
}
else
{
builder.append( object != null ? embedInLinkIfClickable( object.toString() ) : "" );
}
}
private static String embedInLinkIfClickable( String string )
{
// TODO Hardcode "http://" string?
if ( string.startsWith( "http://" ) || string.startsWith( "https://" ) )
{
String anchoredString = "<a href=\"" + string + "\"";
// TODO Hardcoded /node/, /relationship/ string?
String anchorClass = null;
if ( string.contains( "/node/" ) )
{
anchorClass = "node";
}
else if ( string.contains( "/relationship/" ) )
{
anchorClass = "relationship";
}
if ( anchorClass != null )
{
anchoredString += " class=\"" + anchorClass + "\"";
}
anchoredString += ">" + escapeHtml( string ) + "</a>";
string = anchoredString;
}
else
{
string = escapeHtml( string );
}
return string;
}
private static String escapeHtml( final String string )
{
if ( string == null )
{
return null;
}
String res = string.replace( "&", "&" );
res = res.replace( "\"", """ );
res = res.replace( "<", "<" );
res = res.replace( ">", ">" );
return res;
}
public static enum ObjectType
{
NODE,
RELATIONSHIP,
PROPERTIES,
ROOT,
INDEX_ROOT,
;
String getCaption()
{
return name().substring( 0, 1 )
.toUpperCase() + name().substring( 1 )
.toLowerCase();
}
String getHtmlClass()
{
return getCaption().toLowerCase();
}
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_domain_HtmlHelper.java
|
2,860
|
{
@Override
public boolean accept( ConstraintDefinition item )
{
if ( item.isConstraintType( ConstraintType.UNIQUENESS ) )
{
Iterable<String> keys = item.getPropertyKeys();
return single( keys ).equals( propertyKey );
}
else
return false;
}
}, database.getGraph().schema().getConstraints( label( labelName ) ) );
| false
|
community_server_src_test_java_org_neo4j_server_rest_domain_GraphDbHelper.java
|
2,861
|
{
@Override
protected String underlyingObjectToObject( Label object )
{
return object.name();
}
};
| false
|
community_server_src_test_java_org_neo4j_server_rest_domain_GraphDbHelper.java
|
2,862
|
public class GraphDbHelper
{
private final Database database;
public GraphDbHelper( Database database )
{
this.database = database;
}
public int getNumberOfNodes()
{
return numberOfEntitiesFor( Node.class );
}
public int getNumberOfRelationships()
{
return numberOfEntitiesFor( Relationship.class );
}
private int numberOfEntitiesFor( Class<? extends PropertyContainer> type )
{
return (int) database.getGraph().getDependencyResolver().resolveDependency( NodeManager.class )
.getNumberOfIdsInUse( type );
}
public Map<String, Object> getNodeProperties( long nodeId )
{
Transaction tx = database.getGraph().beginTx();
try
{
Node node = database.getGraph().getNodeById( nodeId );
Map<String, Object> allProperties = new HashMap<>();
for ( String propertyKey : node.getPropertyKeys() )
{
allProperties.put( propertyKey, node.getProperty( propertyKey ) );
}
tx.success();
return allProperties;
}
finally
{
tx.finish();
}
}
public void setNodeProperties( long nodeId, Map<String, Object> properties )
{
Transaction tx = database.getGraph().beginTx();
try
{
Node node = database.getGraph().getNodeById( nodeId );
for ( Map.Entry<String, Object> propertyEntry : properties.entrySet() )
{
node.setProperty( propertyEntry.getKey(), propertyEntry.getValue() );
}
tx.success();
}
finally
{
tx.finish();
}
}
public long createNode( Label... labels )
{
Transaction tx = database.getGraph().beginTx();
try
{
Node node = database.getGraph().createNode( labels );
tx.success();
return node.getId();
}
finally
{
tx.finish();
}
}
public long createNode( Map<String, Object> properties, Label... labels )
{
Transaction tx = database.getGraph().beginTx();
try
{
Node node = database.getGraph().createNode( labels );
for ( Map.Entry<String, Object> entry : properties.entrySet() )
{
node.setProperty( entry.getKey(), entry.getValue() );
}
tx.success();
return node.getId();
}
finally
{
tx.finish();
}
}
public void deleteNode( long id )
{
Transaction tx = database.getGraph().beginTx();
try
{
Node node = database.getGraph().getNodeById( id );
node.delete();
tx.success();
}
finally
{
tx.finish();
}
}
public long createRelationship( String type, long startNodeId, long endNodeId )
{
Transaction tx = database.getGraph().beginTx();
try
{
Node startNode = database.getGraph().getNodeById( startNodeId );
Node endNode = database.getGraph().getNodeById( endNodeId );
Relationship relationship = startNode.createRelationshipTo( endNode,
DynamicRelationshipType.withName( type ) );
tx.success();
return relationship.getId();
}
finally
{
tx.finish();
}
}
public long createRelationship( String type )
{
Transaction tx = database.getGraph().beginTx();
try
{
Node startNode = database.getGraph().createNode();
Node endNode = database.getGraph().createNode();
Relationship relationship = startNode.createRelationshipTo( endNode,
DynamicRelationshipType.withName( type ) );
tx.success();
return relationship.getId();
}
finally
{
tx.finish();
}
}
public void setRelationshipProperties( long relationshipId, Map<String, Object> properties )
{
Transaction tx = database.getGraph().beginTx();
try
{
Relationship relationship = database.getGraph().getRelationshipById( relationshipId );
for ( Map.Entry<String, Object> propertyEntry : properties.entrySet() )
{
relationship.setProperty( propertyEntry.getKey(), propertyEntry.getValue() );
}
tx.success();
}
finally
{
tx.finish();
}
}
public Map<String, Object> getRelationshipProperties( long relationshipId )
{
Transaction tx = database.getGraph().beginTx();
try
{
Relationship relationship = database.getGraph().getRelationshipById( relationshipId );
Map<String, Object> allProperties = new HashMap<>();
for ( String propertyKey : relationship.getPropertyKeys() )
{
allProperties.put( propertyKey, relationship.getProperty( propertyKey ) );
}
tx.success();
return allProperties;
}
finally
{
tx.finish();
}
}
public Relationship getRelationship( long relationshipId )
{
Transaction tx = database.getGraph().beginTx();
try
{
Relationship relationship = database.getGraph().getRelationshipById( relationshipId );
tx.success();
return relationship;
}
finally
{
tx.finish();
}
}
public void addNodeToIndex( String indexName, String key, Object value, long id )
{
Transaction tx = database.getGraph().beginTx();
try
{
database.getNodeIndex( indexName ).add( database.getGraph().getNodeById( id ), key, value );
tx.success();
}
finally
{
tx.finish();
}
}
public Collection<Long> queryIndexedNodes( String indexName, String key, Object value )
{
Transaction tx = database.getGraph().beginTx();
try
{
Collection<Long> result = new ArrayList<>();
for ( Node node : database.getNodeIndex( indexName ).query( key, value ) )
{
result.add( node.getId() );
}
tx.success();
return result;
}
finally
{
tx.finish();
}
}
public Collection<Long> getIndexedNodes( String indexName, String key, Object value )
{
Transaction tx = database.getGraph().beginTx();
try
{
Collection<Long> result = new ArrayList<>();
for ( Node node : database.getNodeIndex( indexName ).get( key, value ) )
{
result.add( node.getId() );
}
tx.success();
return result;
}
finally
{
tx.finish();
}
}
public Collection<Long> getIndexedRelationships( String indexName, String key, Object value )
{
Transaction tx = database.getGraph().beginTx();
try
{
Collection<Long> result = new ArrayList<>();
for ( Relationship relationship : database.getRelationshipIndex( indexName ).get( key, value ) )
{
result.add( relationship.getId() );
}
tx.success();
return result;
}
finally
{
tx.finish();
}
}
public void addRelationshipToIndex( String indexName, String key, String value, long relationshipId )
{
Transaction tx = database.getGraph().beginTx();
try
{
Index<Relationship> index = database.getRelationshipIndex( indexName );
index.add( database.getGraph().getRelationshipById( relationshipId ), key, value );
tx.success();
}
finally
{
tx.finish();
}
}
public String[] getNodeIndexes()
{
Transaction transaction = database.getGraph().beginTx();
try
{
return database.getIndexManager()
.nodeIndexNames();
}
finally
{
transaction.finish();
}
}
public Index<Node> createNodeFullTextIndex( String named )
{
Transaction transaction = database.getGraph().beginTx();
try
{
Index<Node> index = database.getIndexManager()
.forNodes( named, MapUtil.stringMap( IndexManager.PROVIDER, "lucene", "type", "fulltext" ) );
transaction.success();
return index;
}
finally
{
transaction.finish();
}
}
public Index<Node> createNodeIndex( String named )
{
Transaction transaction = database.getGraph().beginTx();
try
{
Index<Node> nodeIndex = database.getIndexManager()
.forNodes( named );
transaction.success();
return nodeIndex;
}
finally
{
transaction.finish();
}
}
public String[] getRelationshipIndexes()
{
Transaction transaction = database.getGraph().beginTx();
try
{
return database.getIndexManager()
.relationshipIndexNames();
}
finally
{
transaction.finish();
}
}
public long getFirstNode()
{
Transaction tx = database.getGraph().beginTx();
try
{
try
{
Node referenceNode = database.getGraph().getNodeById(0l);
tx.success();
return referenceNode.getId();
}
catch(NotFoundException e)
{
Node newNode = database.getGraph().createNode();
tx.success();
return newNode.getId();
}
}
finally
{
tx.finish();
}
}
public Index<Relationship> createRelationshipIndex( String named )
{
Transaction transaction = database.getGraph().beginTx();
try
{
RelationshipIndex relationshipIndex = database.getIndexManager()
.forRelationships( named );
transaction.success();
return relationshipIndex;
}
finally
{
transaction.finish();
}
}
public Iterable<String> getNodeLabels( long node )
{
return new IterableWrapper<String, Label>( database.getGraph().getNodeById( node ).getLabels() )
{
@Override
protected String underlyingObjectToObject( Label object )
{
return object.name();
}
};
}
public void addLabelToNode( long node, String labelName )
{
Transaction tx = database.getGraph().beginTx();
try
{
database.getGraph().getNodeById( node ).addLabel( label( labelName ) );
tx.success();
}
finally
{
tx.finish();
}
}
public Iterable<IndexDefinition> getSchemaIndexes( String labelName )
{
return database.getGraph().schema().getIndexes( label( labelName ) );
}
public IndexDefinition createSchemaIndex( String labelName, String propertyKey )
{
Transaction tx = database.getGraph().beginTx();
try
{
IndexDefinition index = database.getGraph().schema().indexFor( label( labelName ) ).on( propertyKey ).create();
tx.success();
return index;
}
finally
{
tx.finish();
}
}
public Iterable<ConstraintDefinition> getPropertyUniquenessConstraints( String labelName, final String propertyKey )
{
Transaction tx = database.getGraph().beginTx();
try
{
Iterable<ConstraintDefinition> definitions = Iterables.filter( new Predicate<ConstraintDefinition>()
{
@Override
public boolean accept( ConstraintDefinition item )
{
if ( item.isConstraintType( ConstraintType.UNIQUENESS ) )
{
Iterable<String> keys = item.getPropertyKeys();
return single( keys ).equals( propertyKey );
}
else
return false;
}
}, database.getGraph().schema().getConstraints( label( labelName ) ) );
tx.success();
return definitions;
}
finally
{
tx.finish();
}
}
public ConstraintDefinition createPropertyUniquenessConstraint( String labelName, List<String> propertyKeys )
{
Transaction tx = database.getGraph().beginTx();
try
{
ConstraintCreator creator = database.getGraph().schema().constraintFor( label( labelName ) );
for ( String propertyKey : propertyKeys )
creator = creator.assertPropertyIsUnique( propertyKey );
ConstraintDefinition result = creator.create();
tx.success();
return result;
}
finally
{
tx.finish();
}
}
public long getLabelCount( long nodeId )
{
Transaction transaction = database.getGraph().beginTx();
try
{
return count( database.getGraph().getNodeById( nodeId ).getLabels());
}
finally
{
transaction.finish();
}
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_domain_GraphDbHelper.java
|
2,863
|
public class GraphDatabaseName
{
public static final GraphDatabaseName NO_NAME = new GraphDatabaseName(
"org.neo4j.rest.domain.GraphDatabaseName.NO_NAME" );
private final String name;
public GraphDatabaseName( String name )
{
this.name = name;
}
public String getName()
{
return name;
}
public String toString()
{
return getName();
}
@Override
public int hashCode()
{
return name != null ? name.hashCode() : 0;
}
public boolean equals( Object obj )
{
return obj instanceof GraphDatabaseName && ( (GraphDatabaseName) obj ).getName()
.equals( name );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_domain_GraphDatabaseName.java
|
2,864
|
private static class ScriptedReturnEvaluator extends ScriptedEvaluator implements Evaluator
{
ScriptedReturnEvaluator( ScriptExecutor executor )
{
super( executor );
}
@Override
public Evaluation evaluate( Path path )
{
return Evaluation.ofIncludes( evalPosition( path ) );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_domain_EvaluatorFactory.java
|
2,865
|
private static class ScriptedPruneEvaluator extends ScriptedEvaluator implements Evaluator
{
ScriptedPruneEvaluator( ScriptExecutor executor )
{
super( executor );
}
@Override
public Evaluation evaluate( Path path )
{
return Evaluation.ofContinues( !evalPosition( path ) );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_domain_EvaluatorFactory.java
|
2,866
|
private static abstract class ScriptedEvaluator
{
private final ScriptExecutor executor;
private final Map<String, Object> scriptContext = new HashMap<>(1);
ScriptedEvaluator( ScriptExecutor executor )
{
this.executor = executor;
}
protected boolean evalPosition(Path path)
{
scriptContext.put( "position", path );
Object out = executor.execute( scriptContext );
if(out instanceof Boolean)
{
return (Boolean)out;
}
throw new EvaluationException("Provided script did not return a boolean value.");
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_domain_EvaluatorFactory.java
|
2,867
|
public class EvaluatorFactory
{
private static final String BUILTIN = "builtin";
private static final String KEY_LANGUAGE = "language";
private static final String KEY_BODY = "body";
private static final String KEY_NAME = "name";
private final ScriptExecutorFactoryRepository factoryRepo;
public EvaluatorFactory( boolean enableSandboxing )
{
Map<String,ScriptExecutor.Factory> languages = new HashMap<>();
languages.put( "javascript", new JavascriptExecutor.Factory( enableSandboxing ) );
factoryRepo = new ScriptExecutorFactoryRepository( languages );
}
public Evaluator pruneEvaluator( Map<String, Object> description )
{
if ( refersToBuiltInEvaluator( description ) )
{
return builtInPruneEvaluator( description );
}
else
{
return new ScriptedPruneEvaluator( getOrCreateExecutorFor(description) );
}
}
public Evaluator returnFilter( Map<String, Object> description )
{
if ( refersToBuiltInEvaluator( description ) )
{
return builtInReturnFilter( description );
}
else
{
return new ScriptedReturnEvaluator( getOrCreateExecutorFor(description) );
}
}
private ScriptExecutor getOrCreateExecutorFor( Map<String, Object> description )
{
String language = (String) description.get( KEY_LANGUAGE );
String body = (String) description.get( KEY_BODY );
return factoryRepo.getFactory(language).createExecutorForScript( body );
}
private static boolean refersToBuiltInEvaluator( Map<String, Object> description )
{
String language = (String) description.get( KEY_LANGUAGE );
return language.equals( BUILTIN );
}
private static Evaluator builtInPruneEvaluator( Map<String, Object> description )
{
String name = (String) description.get( KEY_NAME );
// FIXME I don't like these hardcoded strings
if ( name.equalsIgnoreCase( "none" ) )
{
return null;
}
else
{
throw new EvaluationException( "Unrecognized prune evaluator name '" + name + "'" );
}
}
private static Evaluator builtInReturnFilter( Map<String, Object> description )
{
String name = (String) description.get( KEY_NAME );
// FIXME I don't like these hardcoded strings
if ( name.equalsIgnoreCase( "all" ) )
{
return null;
}
else if ( name.equalsIgnoreCase( "all_but_start_node" ) )
{
return excludeStartPosition();
}
else
{
throw new EvaluationException( "Unrecognized return evaluator name '" + name + "'" );
}
}
private static abstract class ScriptedEvaluator
{
private final ScriptExecutor executor;
private final Map<String, Object> scriptContext = new HashMap<>(1);
ScriptedEvaluator( ScriptExecutor executor )
{
this.executor = executor;
}
protected boolean evalPosition(Path path)
{
scriptContext.put( "position", path );
Object out = executor.execute( scriptContext );
if(out instanceof Boolean)
{
return (Boolean)out;
}
throw new EvaluationException("Provided script did not return a boolean value.");
}
}
private static class ScriptedPruneEvaluator extends ScriptedEvaluator implements Evaluator
{
ScriptedPruneEvaluator( ScriptExecutor executor )
{
super( executor );
}
@Override
public Evaluation evaluate( Path path )
{
return Evaluation.ofContinues( !evalPosition( path ) );
}
}
private static class ScriptedReturnEvaluator extends ScriptedEvaluator implements Evaluator
{
ScriptedReturnEvaluator( ScriptExecutor executor )
{
super( executor );
}
@Override
public Evaluation evaluate( Path path )
{
return Evaluation.ofIncludes( evalPosition( path ) );
}
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_domain_EvaluatorFactory.java
|
2,868
|
@SuppressWarnings( "serial" )
public class EvaluationException extends RuntimeException
{
public EvaluationException()
{
super();
}
public EvaluationException( String message, Throwable cause )
{
super( message, cause );
}
public EvaluationException( String message )
{
super( message );
}
public EvaluationException( Throwable cause )
{
super( cause );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_domain_EvaluationException.java
|
2,869
|
@SuppressWarnings( "serial" )
public class EndNodeNotFoundException extends Exception
{
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_domain_EndNodeNotFoundException.java
|
2,870
|
public class BatchOperationFailedException extends RuntimeException {
private int status;
public BatchOperationFailedException( int status, String message, Exception e ) {
super(message,e);
this.status = status;
}
public int getStatus() {
return status;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_domain_BatchOperationFailedException.java
|
2,871
|
public class DiscoveryServiceTest
{
@Test
public void shouldReturnValidJSONWithDataAndManagementUris() throws Exception
{
Configuration mockConfig = mock( Configuration.class );
String managementUri = "/management";
when(
mockConfig.getString( Configurator.MANAGEMENT_PATH_PROPERTY_KEY,
Configurator.DEFAULT_MANAGEMENT_API_PATH ) ).thenReturn( managementUri );
String dataUri = "/data";
when( mockConfig.getString( Configurator.REST_API_PATH_PROPERTY_KEY, Configurator.DEFAULT_DATA_API_PATH ) ).thenReturn(
dataUri );
String baseUri = "http://www.example.com";
DiscoveryService ds = new DiscoveryService( mockConfig, new EntityOutputFormat( new JsonFormat(), new URI(
baseUri ), null ) );
Response response = ds.getDiscoveryDocument();
String json = new String( (byte[]) response.getEntity() );
assertNotNull( json );
assertThat( json.length(), is( greaterThan( 0 ) ) );
assertThat( json, is( not( "\"\"" ) ) );
assertThat( json, is( not( "null" ) ) );
assertThat( json, containsString( "\"management\" : \"" + baseUri + managementUri + "\"" ) );
assertThat( json, containsString( "\"data\" : \"" + baseUri + dataUri + "\"" ) );
}
@Ignore( "Absolute URIs not supported in this config" )
@Test
public void shouldReturnConfiguredUrlIfConfigIsAbsolute() throws Exception
{
Configuration mockConfig = mock( Configuration.class );
String managementUri = "http://absolutedomain/management";
when(
mockConfig.getString( Configurator.MANAGEMENT_PATH_PROPERTY_KEY,
Configurator.DEFAULT_MANAGEMENT_API_PATH ) ).thenReturn( managementUri );
String dataUri = "http://absolutedomain/management";
when( mockConfig.getString( Configurator.REST_API_PATH_PROPERTY_KEY, Configurator.DEFAULT_DATA_API_PATH ) ).thenReturn(
dataUri );
String baseUri = "http://www.example.com";
DiscoveryService ds = new DiscoveryService( mockConfig, new EntityOutputFormat( new JsonFormat(), new URI(
baseUri ), null ) );
Response response = ds.getDiscoveryDocument();
String json = new String( (byte[]) response.getEntity() );
assertNotNull( json );
assertThat( json.length(), is( greaterThan( 0 ) ) );
assertThat( json, is( not( "\"\"" ) ) );
assertThat( json, is( not( "null" ) ) );
assertThat( json, containsString( "\"management\" : \"" + managementUri + "\"" ) );
assertThat( json, containsString( "\"data\" : \"" + dataUri + "\"" ) );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_discovery_DiscoveryServiceTest.java
|
2,872
|
@Path( "/" )
public class DiscoveryService
{
private static final Logger LOGGER = Log.getLogger(DiscoveryService.class);
private final Configuration configuration;
private final OutputFormat outputFormat;
public DiscoveryService( @Context Configuration configuration, @Context OutputFormat outputFormat )
{
this.configuration = configuration;
this.outputFormat = outputFormat;
}
@GET
@Produces( MediaType.APPLICATION_JSON )
public Response getDiscoveryDocument() throws URISyntaxException
{
String webAdminManagementUri = configuration.getString( Configurator.MANAGEMENT_PATH_PROPERTY_KEY,
Configurator.DEFAULT_MANAGEMENT_API_PATH );
String dataUri = configuration.getString( Configurator.REST_API_PATH_PROPERTY_KEY,
Configurator.DEFAULT_DATA_API_PATH );
DiscoveryRepresentation dr = new DiscoveryRepresentation( webAdminManagementUri, dataUri );
return outputFormat.ok( dr );
}
@GET
@Produces( MediaType.WILDCARD )
public Response redirectToBrowser()
{
try
{
return Response.seeOther( new URI( Configurator.BROWSER_PATH ) )
.build();
}
catch ( URISyntaxException e )
{
LOGGER.warn( e.getMessage() );
return Response.serverError()
.build();
}
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_discovery_DiscoveryService.java
|
2,873
|
return new ServletOutputStream() {
@Override
public void write(int i) throws IOException {
if ( redirectError( i ) ) return;
writeChar( i );
bytesWritten++;
checkHead();
}
};
| false
|
community_server_src_main_java_org_neo4j_server_rest_batch_StreamingBatchOperationResults.java
|
2,874
|
public class StreamingBatchOperationResults
{
public static final int HEAD_BUFFER = 10;
public static final int IS_ERROR = -1;
private final String encoding = "UTF-8";
private final Map<Integer, String> locations = new HashMap<Integer, String>();
private final JsonGenerator g;
private final ServletOutputStream output;
private ByteArrayOutputStream errorStream;
private int bytesWritten = 0;
private char[] head = new char[HEAD_BUFFER];
public StreamingBatchOperationResults( JsonGenerator g, ServletOutputStream output ) throws IOException {
this.g = g;
this.output = output;
g.writeStartArray();
}
public void startOperation(String from, Integer id) throws IOException {
bytesWritten = 0;
g.writeStartObject();
if (id!=null) g.writeNumberField("id", id);
g.writeStringField("from", from);
g.writeRaw(",\"body\":");
g.flush();
}
public void addOperationResult(int status, Integer id,String location) throws IOException {
finishBody();
if ( location != null ) {
locations.put(id, location);
g.writeStringField("location",location);
}
g.writeNumberField("status",status);
g.writeEndObject();
}
private void finishBody() throws IOException
{
if (bytesWritten == 0 ) {
g.writeRaw("null");
} else if ( bytesWritten<HEAD_BUFFER) {
g.writeRaw( head, 0, bytesWritten);
}
}
public ServletOutputStream getServletOutputStream() {
return new ServletOutputStream() {
@Override
public void write(int i) throws IOException {
if ( redirectError( i ) ) return;
writeChar( i );
bytesWritten++;
checkHead();
}
};
}
private boolean redirectError( int i )
{
if ( bytesWritten != IS_ERROR ) return false;
errorStream.write( i );
return true;
}
private void writeChar( int i ) throws IOException
{
if (bytesWritten < HEAD_BUFFER) {
head[bytesWritten]= (char) i;
} else {
output.write( i );
}
}
private void checkHead() throws IOException
{
if (bytesWritten == HEAD_BUFFER) {
if (isJson(head)) {
for ( char c : head )
{
output.write( c );
}
} else {
errorStream = new ByteArrayOutputStream( 1024 );
for ( char c : head )
{
errorStream.write( c );
}
bytesWritten = IS_ERROR;
}
}
}
private boolean isJson( char[] head )
{
return String.valueOf( head ).matches( "\\s*([\\[\"\\{]|true|false).*" );
}
public Map<Integer, String> getLocations()
{
return locations;
}
public void close() throws IOException {
g.writeEndArray();
g.close();
}
public void writeError( int status, String message ) throws IOException {
if (bytesWritten == 0 || bytesWritten == IS_ERROR) g.writeRaw( "null" );
g.writeNumberField( "status", status );
if (message!=null && !message.trim().isEmpty()) g.writeStringField( "message", message);
else {
if (errorStream!=null) {
g.writeStringField( "message", errorStream.toString( encoding ));
}
}
g.close();
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_batch_StreamingBatchOperationResults.java
|
2,875
|
public class NonStreamingBatchOperations extends BatchOperations
{
private BatchOperationResults results;
public NonStreamingBatchOperations( WebServer webServer )
{
super( webServer );
}
public BatchOperationResults performBatchJobs( UriInfo uriInfo, HttpHeaders httpHeaders, InputStream body ) throws IOException, ServletException
{
results = new BatchOperationResults();
parseAndPerform( uriInfo, httpHeaders, body, results.getLocations() );
return results;
}
@Override
protected void invoke( String method, String path, String body, Integer id, URI targetUri, InternalJettyServletRequest req, InternalJettyServletResponse res ) throws IOException, ServletException
{
webServer.invokeDirectly(targetUri.getPath(), req, res);
String resultBody = res.getOutputStream().toString();
if (is2XXStatusCode(res.getStatus()))
{
results.addOperationResult(path, id, resultBody, res.getHeader("Location"));
} else
{
throw new BatchOperationFailedException(res.getStatus(), resultBody, null );
}
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_batch_NonStreamingBatchOperations.java
|
2,876
|
private final BatchOperations ops = new BatchOperations(null) {
@Override
protected void invoke(String method, String path, String body, Integer id, URI targetUri, InternalJettyServletRequest req, InternalJettyServletResponse res) throws IOException, ServletException {
}
};
| false
|
community_server_src_test_java_org_neo4j_server_rest_batch_BatchOperationsTest.java
|
2,877
|
public class BatchOperationsTest {
private final BatchOperations ops = new BatchOperations(null) {
@Override
protected void invoke(String method, String path, String body, Integer id, URI targetUri, InternalJettyServletRequest req, InternalJettyServletResponse res) throws IOException, ServletException {
}
};
@Test
public void testReplaceLocations() throws Exception {
Map<Integer,String> map=new HashMap<Integer, String>();
map.put(100,"bar");
assertEquals("foo", ops.replaceLocationPlaceholders("foo", map));
assertEquals("foo bar", ops.replaceLocationPlaceholders("foo {100}", map));
assertEquals("bar foo bar", ops.replaceLocationPlaceholders("{100} foo {100}", map));
assertEquals("bar bar foo bar bar", ops.replaceLocationPlaceholders("bar {100} foo {100} bar", map));
}
@Test
public void testSchemeInInternalJettyServletRequestForHttp() throws UnsupportedEncodingException
{
// when
InternalJettyServletRequest req = new InternalJettyServletRequest( "POST", "http://localhost:7473/db/data/node", "{'name':'node1'}", new InternalJettyServletResponse() );
// then
assertEquals("http",req.getScheme());
}
@Test
public void testSchemeInInternalJettyServletRequestForHttps() throws UnsupportedEncodingException
{
// when
InternalJettyServletRequest req = new InternalJettyServletRequest( "POST", "https://localhost:7473/db/data/node", "{'name':'node1'}", new InternalJettyServletResponse() );
// then
assertEquals("https",req.getScheme());
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_batch_BatchOperationsTest.java
|
2,878
|
public class DiscoveryRepresentationTest
{
@Test
public void shouldCreateAMapContainingDataAndManagementURIs() throws Exception
{
String managementUri = "/management";
String dataUri = "/data";
DiscoveryRepresentation dr = new DiscoveryRepresentation( managementUri, dataUri );
Map<String, Object> mapOfUris = RepresentationTestAccess.serialize( dr );
Object mappedManagementUri = mapOfUris.get( "management" );
Object mappedDataUri = mapOfUris.get( "data" );
assertNotNull( mappedManagementUri );
assertNotNull( mappedDataUri );
URI baseUri = RepresentationTestBase.BASE_URI;
assertEquals( mappedManagementUri.toString(), Serializer.joinBaseWithRelativePath( baseUri, managementUri ) );
assertEquals( mappedDataUri.toString(), Serializer.joinBaseWithRelativePath( baseUri, dataUri ) );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_repr_DiscoveryRepresentationTest.java
|
2,879
|
public class ExceptionRepresentation extends MappingRepresentation
{
private final Throwable exception;
public ExceptionRepresentation( Throwable exception )
{
super( RepresentationType.EXCEPTION );
this.exception = exception;
}
@Override
protected void serialize( MappingSerializer serializer )
{
String message = exception.getMessage();
if ( message != null )
{
serializer.putString( "message", message );
}
serializer.putString( "exception", exception.getClass().getSimpleName() );
serializer.putString( "fullname", exception.getClass().getName() );
StackTraceElement[] trace = exception.getStackTrace();
if ( trace != null )
{
Collection<String> lines = new ArrayList<String>( trace.length );
for ( StackTraceElement element : trace )
{
if (element.toString().matches( ".*(jetty|jersey|sun\\.reflect|mortbay|javax\\.servlet).*" )) continue;
lines.add( element.toString() );
}
serializer.putList( "stacktrace", ListRepresentation.string( lines ) );
}
Throwable cause = exception.getCause();
if(cause != null)
{
serializer.putMapping( "cause", new ExceptionRepresentation( cause ) );
}
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_ExceptionRepresentation.java
|
2,880
|
public final class ExtensionPointRepresentation extends ObjectRepresentation implements ParameterDescriptionConsumer
{
private final RepresentationType extended;
private final String name;
private final String desciption;
private final List<ParameterRepresentation> parameters = new ArrayList<ParameterRepresentation>();
public ExtensionPointRepresentation( String name, Class<?> extended, String desciption )
{
super( RepresentationType.PLUGIN_DESCRIPTION );
this.name = name;
this.desciption = desciption;
this.extended = RepresentationType.extended( extended );
}
@Override
public void describeParameter( String name, Class<?> type, boolean optional, String description )
{
parameters.add( new ParameterRepresentation( name, type, optional, description, false ) );
}
@Override
public void describeListParameter( String name, Class<?> type, boolean optional, String description )
{
parameters.add( new ParameterRepresentation( name, type, optional, description, true ) );
}
public String getName()
{
return name;
}
public String getExtendedEntity()
{
return extended.valueName;
}
@Mapping( "name" )
public ValueRepresentation methodName()
{
return ValueRepresentation.string( name );
}
@Mapping( "description" )
public ValueRepresentation description()
{
return ValueRepresentation.string( desciption );
}
@Mapping( "extends" )
public ValueRepresentation extendedEntity()
{
return ValueRepresentation.string( getExtendedEntity() );
}
@Mapping( "parameters" )
public ListRepresentation parametersList()
{
return new ListRepresentation( RepresentationType.PLUGIN_PARAMETER, parameters );
}
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,881
|
public final class RepresentationType
{
private static final Map<Class<?>, Class<?>> boxed = new HashMap<>();
static
{
boxed.put( byte.class, Byte.class );
boxed.put( char.class, Character.class );
boxed.put( short.class, Short.class );
boxed.put( int.class, Integer.class );
boxed.put( long.class, Long.class );
boxed.put( float.class, Float.class );
boxed.put( double.class, Double.class );
boxed.put( boolean.class, Boolean.class );
}
private static final Map<String, RepresentationType> types = new HashMap<>();
private static final Map<Class<?>, RepresentationType> extended = new HashMap<>();
// Graph database types
public static final RepresentationType
GRAPHDB = new RepresentationType( "graphdb", null, GraphDatabaseService.class ),
NODE = new RepresentationType( "node", "nodes", Node.class ),
RELATIONSHIP = new RepresentationType( "relationship", "relationships", Relationship.class ),
PATH = new RepresentationType( "path", "paths", Path.class ),
FULL_PATH = new RepresentationType( "full-path", "full-paths", FullPath.class),
RELATIONSHIP_TYPE = new RepresentationType( "relationship-type", "relationship-types", RelationshipType.class ),
PROPERTIES = new RepresentationType( "properties" ),
INDEX = new RepresentationType( "index" ),
NODE_INDEX_ROOT = new RepresentationType( "node-index" ),
RELATIONSHIP_INDEX_ROOT = new RepresentationType( "relationship-index" ),
INDEX_DEFINITION = new RepresentationType( "index-definition", "index-definitions", IndexDefinition.class ),
CONSTRAINT_DEFINITION = new RepresentationType( "constraint-definition", "constraint-definitions", ConstraintDefinition.class ),
PLUGINS = new RepresentationType( "plugins" ),
PLUGIN = new RepresentationType( "plugin" ),
PLUGIN_DESCRIPTION = new RepresentationType( "plugin-point" ),
SERVER_PLUGIN_DESCRIPTION = new RepresentationType( "server-plugin", null ),
PLUGIN_PARAMETER = new RepresentationType( "plugin-parameter", "plugin-parameter-list" ),
// Value types
URI = new RepresentationType( "uri", null ),
TEMPLATE = new RepresentationType( "uri-template" ),
STRING = new RepresentationType( "string", "strings", String.class ),
// primitives
BYTE = new RepresentationType( "byte", "bytes", byte.class ),
CHAR = new RepresentationType( "character", "characters", char.class ),
SHORT = new RepresentationType( "short", "shorts", short.class ),
INTEGER = new RepresentationType( "integer", "integers", int.class ),
LONG = new RepresentationType( "long", "longs", long.class ),
FLOAT = new RepresentationType( "float", "floats", float.class ),
DOUBLE = new RepresentationType( "double", "doubles", double.class ),
BOOLEAN = new RepresentationType( "boolean", "booleans", boolean.class ),
NOTHING = new RepresentationType( "void", null ),
// System
EXCEPTION = new RepresentationType( "exception" ),
MAP = new RepresentationType( "map", "maps", Map.class ),
NULL = new RepresentationType( "null", "nulls", Object.class );
final String valueName;
final String listName;
final Class<?> extend;
private RepresentationType( String valueName, String listName )
{
this( valueName, listName, null );
}
private RepresentationType( String valueName, String listName, Class<?> extend )
{
this.valueName = valueName;
this.listName = listName;
this.extend = extend;
if ( valueName != null )
{
types.put( valueName.replace( "-", "" ), this );
}
if ( extend != null )
{
extended.put( extend, this );
if ( extend.isPrimitive() )
{
extended.put( boxed.get( extend ), this );
}
}
}
RepresentationType( String type )
{
if ( type == null )
{
throw new IllegalArgumentException( "type may not be null" );
}
this.valueName = type;
this.listName = type + "s";
this.extend = null;
}
@Override
public String toString()
{
return valueName;
}
static RepresentationType valueOf( Class<? extends Number> type )
{
return types.get( type.getSimpleName().toLowerCase() );
}
@Override
public int hashCode()
{
if ( valueName == null )
{
return listName.hashCode();
}
return valueName.hashCode();
}
@Override
public boolean equals( Object obj )
{
if ( obj instanceof RepresentationType )
{
RepresentationType that = (RepresentationType) obj;
if ( this.valueName != null )
{
if ( valueName.equals( that.valueName ) )
{
if ( this.listName != null )
{
return listName.equals( that.listName );
}
else
{
return that.listName == null;
}
}
}
else if ( this.listName != null )
{
return that.valueName == null && listName.equals( that.listName );
}
}
return false;
}
static RepresentationType extended( Class<?> extend )
{
return extended.get( extend );
}
}
| false
|
community_server-api_src_main_java_org_neo4j_server_rest_repr_RepresentationType.java
|
2,882
|
private static class StringFormat extends RepresentationFormat
{
StringFormat()
{
super( MediaType.WILDCARD_TYPE );
}
@Override
protected String serializeValue( String type, Object value )
{
return value.toString();
}
@Override
protected String complete( ListWriter serializer )
{
throw new UnsupportedOperationException( "StringFormat.complete(ListWriter)" );
}
@Override
protected String complete( MappingWriter serializer )
{
throw new UnsupportedOperationException( "StringFormat.complete(MappingWriter)" );
}
@Override
protected ListWriter serializeList( String type )
{
throw new UnsupportedOperationException( "StringFormat.serializeList()" );
}
@Override
protected MappingWriter serializeMapping( String type )
{
throw new UnsupportedOperationException( "StringFormat.serializeMapping()" );
}
@Override
public List<Object> readList( String input )
{
throw new UnsupportedOperationException( "StringFormat.readList()" );
}
@Override
public Map<String, Object> readMap( String input, String... requiredKeys )
{
throw new UnsupportedOperationException( "StringFormat.readMap()" );
}
@Override
public Object readValue( String input )
{
throw new UnsupportedOperationException( "StringFormat.readValue()" );
}
@Override
public URI readUri( String input )
{
throw new UnsupportedOperationException( "StringFormat.readUri()" );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_repr_RepresentationTestAccess.java
|
2,883
|
public class RepresentationTestAccess
{
private static final URI BASE_URI = URI.create( "http://neo4j.org/" );
public static Object serialize( Representation repr )
{
if ( repr instanceof ValueRepresentation )
{
return serialize( (ValueRepresentation) repr );
}
else if ( repr instanceof MappingRepresentation )
{
return serialize( (MappingRepresentation) repr );
}
else if ( repr instanceof ListRepresentation )
{
return serialize( (ListRepresentation) repr );
}
else
{
throw new IllegalArgumentException( repr.getClass().toString() );
}
}
public static String serialize( ValueRepresentation repr )
{
return serialize( BASE_URI, repr );
}
public static String serialize( URI baseUri, ValueRepresentation repr )
{
return repr.serialize( new StringFormat(), baseUri, null );
}
public static Map<String, Object> serialize( MappingRepresentation repr )
{
return serialize( BASE_URI, repr );
}
public static Map<String, Object> serialize( URI baseUri, MappingRepresentation repr )
{
Map<String, Object> result = new HashMap<String, Object>();
repr.serialize( new MappingSerializer( new MapWrappingWriter( result ), baseUri, null ) );
return result;
}
public static List<Object> serialize( ListRepresentation repr )
{
return serialize( BASE_URI, repr );
}
public static List<Object> serialize( URI baseUri, ListRepresentation repr )
{
List<Object> result = new ArrayList<Object>();
repr.serialize( new ListSerializer( new ListWrappingWriter( result ), baseUri, null ) );
return result;
}
public static long nodeUriToId( String nodeUri )
{
int lastSlash = nodeUri.lastIndexOf( '/' );
if ( lastSlash == -1 )
throw new IllegalArgumentException( "'" + nodeUri + "' isn't a node URI" );
return Long.parseLong( nodeUri.substring( lastSlash+1 ) );
}
private static class StringFormat extends RepresentationFormat
{
StringFormat()
{
super( MediaType.WILDCARD_TYPE );
}
@Override
protected String serializeValue( String type, Object value )
{
return value.toString();
}
@Override
protected String complete( ListWriter serializer )
{
throw new UnsupportedOperationException( "StringFormat.complete(ListWriter)" );
}
@Override
protected String complete( MappingWriter serializer )
{
throw new UnsupportedOperationException( "StringFormat.complete(MappingWriter)" );
}
@Override
protected ListWriter serializeList( String type )
{
throw new UnsupportedOperationException( "StringFormat.serializeList()" );
}
@Override
protected MappingWriter serializeMapping( String type )
{
throw new UnsupportedOperationException( "StringFormat.serializeMapping()" );
}
@Override
public List<Object> readList( String input )
{
throw new UnsupportedOperationException( "StringFormat.readList()" );
}
@Override
public Map<String, Object> readMap( String input, String... requiredKeys )
{
throw new UnsupportedOperationException( "StringFormat.readMap()" );
}
@Override
public Object readValue( String input )
{
throw new UnsupportedOperationException( "StringFormat.readValue()" );
}
@Override
public URI readUri( String input )
{
throw new UnsupportedOperationException( "StringFormat.readUri()" );
}
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_repr_RepresentationTestAccess.java
|
2,884
|
{
@Override
public Response.ResponseBuilder answer( InvocationOnMock invocationOnMock ) throws Throwable
{
ref.set( (StreamingOutput) invocationOnMock.getArguments()[0] );
return responseBuilder;
}
} );
| false
|
community_server_src_test_java_org_neo4j_server_rest_repr_RepresentationFormatRepositoryTest.java
|
2,885
|
public class RepresentationFormatRepositoryTest
{
private final RepresentationFormatRepository repository = new RepresentationFormatRepository( null );
@Test
public void canProvideJsonFormat() throws Exception
{
assertNotNull( repository.inputFormat( MediaType.valueOf( "application/json" ) ) );
}
@Test
public void canProvideUTF8EncodedJsonFormat() throws Exception
{
assertNotNull( repository.inputFormat( MediaType.valueOf( "application/json;charset=UTF-8" ) ) );
}
@Test( expected = MediaTypeNotSupportedException.class )
public void canNotGetInputFormatBasedOnWildcardMediaType() throws Exception
{
InputFormat format = repository.inputFormat( MediaType.WILDCARD_TYPE );
format.readValue( "foo" );
fail( "Got InputFormat based on wild card type: " + format );
}
@Test
public void canProvideJsonOutputFormat() throws Exception
{
OutputFormat format = repository.outputFormat( asList( MediaType.APPLICATION_JSON_TYPE ), null, null );
assertNotNull( format );
assertEquals( "\"test\"", format.assemble( ValueRepresentation.string( "test" ) ) );
}
@Test
public void cannotProvideStreamingForOtherMediaTypes() throws Exception
{
final Response.ResponseBuilder responseBuilder = mock( Response.ResponseBuilder.class );
// no streaming
when( responseBuilder.entity( anyString() ) ).thenReturn( responseBuilder );
Mockito.verify( responseBuilder, never() ).entity( isA( StreamingOutput.class ) );
when( responseBuilder.type( Matchers.<MediaType> any() ) ).thenReturn( responseBuilder );
when( responseBuilder.build() ).thenReturn( null );
OutputFormat format = repository.outputFormat( asList( MediaType.TEXT_HTML_TYPE ),
new URI( "http://some.host" ), streamingHeader() );
assertNotNull( format );
format.response( responseBuilder, new ExceptionRepresentation( new RuntimeException() ) );
}
@Test
public void canProvideStreamingJsonOutputFormat() throws Exception
{
Response response = mock( Response.class );
final AtomicReference<StreamingOutput> ref = new AtomicReference<>();
final Response.ResponseBuilder responseBuilder = mockResponsBuilder( response, ref );
OutputFormat format = repository.outputFormat( asList( MediaType.APPLICATION_JSON_TYPE ), null,
streamingHeader() );
assertNotNull( format );
Response returnedResponse = format.response( responseBuilder, new MapRepresentation( map( "a", "test" ) ) );
assertSame( response, returnedResponse );
StreamingOutput streamingOutput = ref.get();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
streamingOutput.write( baos );
assertEquals( "{\"a\":\"test\"}", baos.toString() );
}
private Response.ResponseBuilder mockResponsBuilder( Response response, final AtomicReference<StreamingOutput> ref )
{
final Response.ResponseBuilder responseBuilder = mock( Response.ResponseBuilder.class );
when( responseBuilder.entity( Matchers.isA( StreamingOutput.class ) ) ).thenAnswer(
new Answer<Response.ResponseBuilder>()
{
@Override
public Response.ResponseBuilder answer( InvocationOnMock invocationOnMock ) throws Throwable
{
ref.set( (StreamingOutput) invocationOnMock.getArguments()[0] );
return responseBuilder;
}
} );
when( responseBuilder.type( Matchers.<MediaType> any() ) ).thenReturn( responseBuilder );
when( responseBuilder.build() ).thenReturn( response );
return responseBuilder;
}
@SuppressWarnings( "unchecked" )
private MultivaluedMap<String, String> streamingHeader()
{
MultivaluedMap<String, String> headers = mock( MultivaluedMap.class );
when( headers.getFirst( StreamingFormat.STREAM_HEADER ) ).thenReturn( "true" );
return headers;
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_repr_RepresentationFormatRepositoryTest.java
|
2,886
|
public final class RepresentationFormatRepository
{
private final Map<MediaType, RepresentationFormat> formats;
private final AbstractNeoServer injectorProvider;
public RepresentationFormatRepository( AbstractNeoServer injectorProvider )
{
this.injectorProvider = injectorProvider;
this.formats = new HashMap<MediaType, RepresentationFormat>();
for ( RepresentationFormat format : Service.load( RepresentationFormat.class ) )
{
formats.put( format.mediaType, format );
}
}
public OutputFormat outputFormat(List<MediaType> acceptable, URI baseUri, MultivaluedMap<String, String> requestHeaders)
{
RepresentationFormat format = forHeaders( acceptable, requestHeaders );
if (format==null)
{
format = forMediaTypes( acceptable );
}
if (format==null)
{
format = useDefault( acceptable );
}
return new OutputFormat( format, baseUri, getExtensionManager() );
}
private PluginManager getExtensionManager()
{
return injectorProvider==null ? null : injectorProvider.getExtensionManager();
}
private RepresentationFormat forHeaders(List<MediaType> acceptable, MultivaluedMap<String, String> requestHeaders)
{
if (requestHeaders==null) return null;
if (!containsType(acceptable,MediaType.APPLICATION_JSON_TYPE)) return null;
String streamHeader = requestHeaders.getFirst(StreamingFormat.STREAM_HEADER);
if ("true".equalsIgnoreCase(streamHeader))
{
return formats.get(StreamingFormat.MEDIA_TYPE);
}
return null;
}
private boolean containsType(List<MediaType> mediaTypes, MediaType mediaType)
{
for (MediaType type : mediaTypes)
{
if (mediaType.getType().equals(type.getType()) && mediaType.getSubtype().equals(type.getSubtype())) return true;
}
return false;
}
private RepresentationFormat forMediaTypes(List<MediaType> acceptable)
{
for ( MediaType type : acceptable )
{
RepresentationFormat format = formats.get( type );
if ( format != null )
{
return format;
}
}
return null;
}
public InputFormat inputFormat( MediaType type )
{
if ( type == null )
{
return useDefault();
}
RepresentationFormat format = formats.get( type );
if ( format != null )
{
return format;
}
format = formats.get( new MediaType( type.getType(), type.getSubtype() ) );
if ( format != null )
{
return format;
}
return useDefault( type );
}
private DefaultFormat useDefault( final List<MediaType> acceptable )
{
return useDefault( acceptable.toArray( new MediaType[acceptable.size()] ) );
}
private DefaultFormat useDefault( final MediaType... type )
{
return new DefaultFormat( new JsonFormat(), formats.keySet(), type );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_RepresentationFormatRepository.java
|
2,887
|
{
@Override
protected Boolean convertBoolean( Object value ) throws BadInputException
{
return RepresentationFormat.this.convertBoolean( value );
}
@Override
protected Byte convertByte( Object value ) throws BadInputException
{
return RepresentationFormat.this.convertByte( value );
}
@Override
protected Character convertCharacter( Object value ) throws BadInputException
{
return RepresentationFormat.this.convertCharacter( value );
}
@Override
protected Double convertDouble( Object value ) throws BadInputException
{
return RepresentationFormat.this.convertDouble( value );
}
@Override
protected Float convertFloat( Object value ) throws BadInputException
{
return RepresentationFormat.this.convertFloat( value );
}
@Override
protected Integer convertInteger( Object value ) throws BadInputException
{
return RepresentationFormat.this.convertInteger( value );
}
@Override
protected Long convertLong( Object value ) throws BadInputException
{
return RepresentationFormat.this.convertLong( value );
}
@Override
protected Node convertNode( GraphDatabaseAPI graphDb, Object value )
throws BadInputException
{
return RepresentationFormat.this.convertNode( graphDb, value );
}
@Override
protected Relationship convertRelationship( GraphDatabaseAPI graphDb, Object value )
throws BadInputException
{
return RepresentationFormat.this.convertRelationship( graphDb, value );
}
@Override
protected Short convertShort( Object value ) throws BadInputException
{
return RepresentationFormat.this.convertShort( value );
}
@Override
protected String convertString( Object value ) throws BadInputException
{
return RepresentationFormat.this.convertString( value );
}
@Override
protected URI convertURI( Object value ) throws BadInputException
{
return RepresentationFormat.this.convertURI( value );
}
};
| false
|
community_server-api_src_main_java_org_neo4j_server_rest_repr_RepresentationFormat.java
|
2,888
|
public abstract class RepresentationFormat implements InputFormat
{
final MediaType mediaType;
public RepresentationFormat( MediaType mediaType )
{
this.mediaType = mediaType;
}
@Override
public String toString()
{
return String.format( "%s[%s]", getClass().getSimpleName(), mediaType );
}
String serializeValue( RepresentationType type, Object value )
{
return serializeValue( type.valueName, value );
}
protected abstract String serializeValue( String type, Object value );
ListWriter serializeList( RepresentationType type )
{
if ( type.listName == null )
throw new IllegalStateException( "Invalid list type: " + type );
return serializeList( type.listName );
}
protected abstract ListWriter serializeList( String type );
MappingWriter serializeMapping( RepresentationType type )
{
return serializeMapping( type.valueName );
}
protected abstract MappingWriter serializeMapping( String type );
/**
* Will be invoked (when serialization is done) with the result retrieved
* from invoking {@link #serializeList(String)}, it is therefore safe for
* this method to convert the {@link ListWriter} argument to the
* implementation class returned by {@link #serializeList(String)}.
*/
protected abstract String complete( ListWriter serializer ) ;
/**
* Will be invoked (when serialization is done) with the result retrieved
* from invoking {@link #serializeMapping(String)}, it is therefore safe for
* this method to convert the {@link MappingWriter} argument to the
* implementation class returned by {@link #serializeMapping(String)}.
*/
protected abstract String complete( MappingWriter serializer ) ;
@Override
public ParameterList readParameterList( String input ) throws BadInputException
{
return new ParameterList( readMap( input ) )
{
@Override
protected Boolean convertBoolean( Object value ) throws BadInputException
{
return RepresentationFormat.this.convertBoolean( value );
}
@Override
protected Byte convertByte( Object value ) throws BadInputException
{
return RepresentationFormat.this.convertByte( value );
}
@Override
protected Character convertCharacter( Object value ) throws BadInputException
{
return RepresentationFormat.this.convertCharacter( value );
}
@Override
protected Double convertDouble( Object value ) throws BadInputException
{
return RepresentationFormat.this.convertDouble( value );
}
@Override
protected Float convertFloat( Object value ) throws BadInputException
{
return RepresentationFormat.this.convertFloat( value );
}
@Override
protected Integer convertInteger( Object value ) throws BadInputException
{
return RepresentationFormat.this.convertInteger( value );
}
@Override
protected Long convertLong( Object value ) throws BadInputException
{
return RepresentationFormat.this.convertLong( value );
}
@Override
protected Node convertNode( GraphDatabaseAPI graphDb, Object value )
throws BadInputException
{
return RepresentationFormat.this.convertNode( graphDb, value );
}
@Override
protected Relationship convertRelationship( GraphDatabaseAPI graphDb, Object value )
throws BadInputException
{
return RepresentationFormat.this.convertRelationship( graphDb, value );
}
@Override
protected Short convertShort( Object value ) throws BadInputException
{
return RepresentationFormat.this.convertShort( value );
}
@Override
protected String convertString( Object value ) throws BadInputException
{
return RepresentationFormat.this.convertString( value );
}
@Override
protected URI convertURI( Object value ) throws BadInputException
{
return RepresentationFormat.this.convertURI( value );
}
};
}
protected Relationship convertRelationship( GraphDatabaseAPI graphDb, Object value )
throws BadInputException
{
if ( value instanceof Relationship )
{
return (Relationship) value;
}
if ( value instanceof URI )
{
try
{
return getRelationship( graphDb, (URI) value );
}
catch ( RelationshipNotFoundException e )
{
throw new BadInputException( e );
}
}
if ( value instanceof String )
{
try
{
return getRelationship( graphDb, (String) value );
}
catch ( RelationshipNotFoundException e )
{
throw new BadInputException( e );
}
}
throw new BadInputException( "Could not convert!" );
}
protected Node convertNode( GraphDatabaseAPI graphDb, Object value )
throws BadInputException
{
if ( value instanceof Node )
{
return (Node) value;
}
if ( value instanceof URI )
{
try
{
return getNode( graphDb, (URI) value );
}
catch ( NodeNotFoundException e )
{
throw new BadInputException( e );
}
}
if ( value instanceof String )
{
try
{
return getNode( graphDb, (String) value );
}
catch ( NodeNotFoundException e )
{
throw new BadInputException( e );
}
}
throw new BadInputException( "Could not convert!" );
}
protected Node getNode( GraphDatabaseAPI graphDb, String value ) throws BadInputException,
NodeNotFoundException
{
try
{
return getNode( graphDb, new URI( value ) );
}
catch ( URISyntaxException e )
{
throw new BadInputException( e );
}
}
protected Node getNode( GraphDatabaseAPI graphDb, URI uri ) throws BadInputException,
NodeNotFoundException
{
try
{
return graphDb.getNodeById( extractId( uri ) );
}
catch ( NotFoundException e )
{
throw new NodeNotFoundException(e);
}
}
private long extractId( URI uri ) throws BadInputException
{
String[] path = uri.getPath().split( "/" );
try
{
return Long.parseLong( path[path.length - 1] );
}
catch ( NumberFormatException e )
{
throw new BadInputException( e );
}
}
private Relationship getRelationship( GraphDatabaseAPI graphDb, String value )
throws BadInputException, RelationshipNotFoundException
{
try
{
return getRelationship( graphDb, new URI( value ) );
}
catch ( URISyntaxException e )
{
throw new BadInputException( e );
}
}
protected Relationship getRelationship( GraphDatabaseAPI graphDb, URI uri )
throws BadInputException, RelationshipNotFoundException
{
try
{
return graphDb.getRelationshipById( extractId( uri ) );
}
catch ( NotFoundException e )
{
throw new RelationshipNotFoundException();
}
}
protected URI convertURI( Object value ) throws BadInputException
{
if ( value instanceof URI )
{
return (URI) value;
}
if ( value instanceof String )
{
try
{
return new URI( (String) value );
}
catch ( URISyntaxException e )
{
throw new BadInputException( e );
}
}
throw new BadInputException( "Could not convert!" );
}
protected String convertString( Object value ) throws BadInputException
{
if ( value instanceof String )
{
return (String) value;
}
throw new BadInputException( "Could not convert!" );
}
@SuppressWarnings( "boxing" )
protected Short convertShort( Object value ) throws BadInputException
{
if ( value instanceof Number && !( value instanceof Float || value instanceof Double ) )
{
short primitive = ( (Number) value ).shortValue();
if ( primitive != ( (Number) value ).longValue() )
throw new BadInputException( "Input did not fit in short" );
return primitive;
}
if ( value instanceof String )
{
try
{
return Short.parseShort( (String) value );
}
catch ( NumberFormatException e )
{
throw new BadInputException( e );
}
}
throw new BadInputException( "Could not convert!" );
}
@SuppressWarnings( "boxing" )
protected Long convertLong( Object value ) throws BadInputException
{
if ( value instanceof Number && !( value instanceof Float || value instanceof Double ) )
{
long primitive = ( (Number) value ).longValue();
return primitive;
}
if ( value instanceof String )
{
try
{
return Long.parseLong( (String) value );
}
catch ( NumberFormatException e )
{
throw new BadInputException( e );
}
}
throw new BadInputException( "Could not convert!" );
}
@SuppressWarnings( "boxing" )
protected Integer convertInteger( Object value ) throws BadInputException
{
if ( value instanceof Number && !( value instanceof Float || value instanceof Double ) )
{
int primitive = ( (Number) value ).intValue();
if ( primitive != ( (Number) value ).longValue() )
throw new BadInputException( "Input did not fit in int" );
return primitive;
}
if ( value instanceof String )
{
try
{
return Integer.parseInt( (String) value );
}
catch ( NumberFormatException e )
{
throw new BadInputException( e );
}
}
throw new BadInputException( "Could not convert!" );
}
@SuppressWarnings( "boxing" )
protected Float convertFloat( Object value ) throws BadInputException
{
if ( value instanceof Number )
{
return ( (Number) value ).floatValue();
}
if ( value instanceof String )
{
try
{
return Float.parseFloat( (String) value );
}
catch ( NumberFormatException e )
{
throw new BadInputException( e );
}
}
throw new BadInputException( "Could not convert!" );
}
@SuppressWarnings( "boxing" )
protected Double convertDouble( Object value ) throws BadInputException
{
if ( value instanceof Number )
{
return ( (Number) value ).doubleValue();
}
if ( value instanceof String )
{
try
{
return Double.parseDouble( (String) value );
}
catch ( NumberFormatException e )
{
throw new BadInputException( e );
}
}
throw new BadInputException( "Could not convert!" );
}
@SuppressWarnings( "boxing" )
protected Character convertCharacter( Object value ) throws BadInputException
{
if ( value instanceof Character )
{
return (Character) value;
}
if ( value instanceof Number )
{
int primitive = ( (Number) value ).intValue();
if ( primitive != ( (Number) value ).longValue() || ( primitive > 0xFFFF ) )
throw new BadInputException( "Input did not fit in char" );
return Character.valueOf( (char) primitive );
}
if ( value instanceof String && ( (String) value ).length() == 1 )
{
return ( (String) value ).charAt( 0 );
}
throw new BadInputException( "Could not convert!" );
}
@SuppressWarnings( "boxing" )
protected Byte convertByte( Object value ) throws BadInputException
{
if ( value instanceof Number )
{
byte primitive = ( (Number) value ).byteValue();
if ( primitive != ( (Number) value ).longValue() )
throw new BadInputException( "Input did not fit in byte" );
return primitive;
}
if ( value instanceof String )
{
try
{
return Byte.parseByte( (String) value );
}
catch ( NumberFormatException e )
{
throw new BadInputException( e );
}
}
throw new BadInputException( "Could not convert!" );
}
@SuppressWarnings( "boxing" )
protected Boolean convertBoolean( Object value ) throws BadInputException
{
if ( value instanceof Boolean )
{
return (Boolean) value;
}
if ( value instanceof String )
{
try
{
return Boolean.parseBoolean( (String) value );
}
catch ( NumberFormatException e )
{
throw new BadInputException( e );
}
}
throw new BadInputException( "Could not convert!" );
}
public void complete() {
}
}
| false
|
community_server-api_src_main_java_org_neo4j_server_rest_repr_RepresentationFormat.java
|
2,889
|
public class RepresentationExceptionHandlingIterable<T> extends ExceptionHandlingIterable<T> {
public RepresentationExceptionHandlingIterable(Iterable<T> source) {
super(source);
}
@Override
protected Iterator<T> exceptionOnIterator(Throwable t) {
if (t instanceof Exception) rethrow(new BadInputException(t));
return super.exceptionOnIterator(t);
}
@Override
protected T exceptionOnNext(Throwable t) {
if (t instanceof Exception) rethrow(new BadInputException(t));
return super.exceptionOnNext(t);
}
@Override
protected void exceptionOnRemove(Throwable t) {
super.exceptionOnRemove(t);
}
@Override
protected boolean exceptionOnHasNext(Throwable t) {
if (t instanceof Exception) rethrow(new BadInputException(t));
return super.exceptionOnHasNext(t);
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_RepresentationExceptionHandlingIterable.java
|
2,890
|
public abstract class RepresentationDispatcher extends PropertyTypeDispatcher<String, Representation>
{
@Override
protected Representation dispatchBooleanProperty( boolean property, String param )
{
return bool( property );
}
@Override
protected Representation dispatchDoubleProperty( double property, String param )
{
return number( property );
}
@Override
protected Representation dispatchFloatProperty( float property, String param )
{
return number( property );
}
@Override
protected Representation dispatchIntegerProperty( int property, String param )
{
return number( property );
}
@Override
protected Representation dispatchLongProperty( long property, String param )
{
return number( property );
}
@Override
protected Representation dispatchShortProperty( short property, String param )
{
return number( property );
}
@Override
protected Representation dispatchStringProperty( String property, String param )
{
return string( property );
}
@Override
protected Representation dispatchStringArrayProperty( String[] array, String param )
{
ArrayList<Representation> values = new ArrayList<>();
for ( String z : array )
{
values.add( string( z ) );
}
return new ListRepresentation( "", values );
}
@Override
@SuppressWarnings( "boxing" )
protected Representation dispatchShortArrayProperty( PropertyArray<short[], Short> array, String param )
{
ArrayList<Representation> values = new ArrayList<>();
for ( Short z : array )
{
values.add( number( z ) );
}
return new ListRepresentation( "", values );
}
@Override
@SuppressWarnings( "boxing" )
protected Representation dispatchIntegerArrayProperty( PropertyArray<int[], Integer> array, String param )
{
ArrayList<Representation> values = new ArrayList<>();
for ( Integer z : array )
{
values.add( number( z ) );
}
return new ListRepresentation( "", values );
}
@Override
@SuppressWarnings( "boxing" )
protected Representation dispatchLongArrayProperty( PropertyArray<long[], Long> array, String param )
{
ArrayList<Representation> values = new ArrayList<>();
for ( Long z : array )
{
values.add( number( z ) );
}
return new ListRepresentation( "", values );
}
@Override
@SuppressWarnings( "boxing" )
protected Representation dispatchFloatArrayProperty( PropertyArray<float[], Float> array, String param )
{
ArrayList<Representation> values = new ArrayList<>();
for ( Float z : array )
{
values.add( number( z ) );
}
return new ListRepresentation( "", values );
}
@Override
@SuppressWarnings( "boxing" )
protected Representation dispatchDoubleArrayProperty( PropertyArray<double[], Double> array, String param )
{
ArrayList<Representation> values = new ArrayList<>();
for ( Double z : array )
{
values.add( number( z ) );
}
return new ListRepresentation( "", values );
}
@Override
@SuppressWarnings( "boxing" )
protected Representation dispatchBooleanArrayProperty( PropertyArray<boolean[], Boolean> array, String param )
{
ArrayList<Representation> values = new ArrayList<>();
for ( Boolean z : array )
{
values.add( bool( z ) );
}
return new ListRepresentation( "", values );
}
@Override
protected Representation dispatchByteProperty( byte property, String param )
{
throw new UnsupportedOperationException( "Representing bytes not implemented." );
}
@Override
protected Representation dispatchCharacterProperty( char property, String param )
{
return number( property );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_RepresentationDispatcher.java
|
2,891
|
{
@Override
boolean isEmpty()
{
return true;
}
@Override
String serialize( RepresentationFormat format, URI baseUri, ExtensionInjector extensions )
{
return "";
}
@Override
void putTo( MappingSerializer serializer, String key )
{
}
@Override
void addTo( ListSerializer serializer )
{
}
};
| false
|
community_server-api_src_main_java_org_neo4j_server_rest_repr_Representation.java
|
2,892
|
public abstract class Representation
{
// non-inlineable constants
public static final String GRAPHDB = RepresentationType.GRAPHDB.valueName;
public static final String INDEX = RepresentationType.INDEX.valueName;
public static final String NODE_INDEXES = RepresentationType.NODE_INDEX_ROOT.valueName;
public static final String RELATIONSHIP_INDEXES = RepresentationType.RELATIONSHIP_INDEX_ROOT.valueName;
public static final String NODE = RepresentationType.NODE.valueName;
public static final String NODE_LIST = RepresentationType.NODE.listName;
public static final String RELATIONSHIP = RepresentationType.RELATIONSHIP.valueName;
public static final String RELATIONSHIP_LIST = RepresentationType.RELATIONSHIP.listName;
public static final String PATH = RepresentationType.PATH.valueName;
public static final String PATH_LIST = RepresentationType.PATH.listName;
public static final String RELATIONSHIP_TYPE = RepresentationType.RELATIONSHIP_TYPE.valueName;
public static final String PROPERTIES_MAP = RepresentationType.PROPERTIES.valueName;
public static final String EXTENSIONS_MAP = RepresentationType.PLUGINS.valueName;
public static final String EXTENSION = RepresentationType.PLUGIN.valueName;
public static final String URI = RepresentationType.URI.valueName;
public static final String URI_TEMPLATE = RepresentationType.TEMPLATE.valueName;
public static final String STRING = RepresentationType.STRING.valueName;
public static final String STRING_LIST = RepresentationType.STRING.listName;
public static final String BYTE = RepresentationType.BYTE.valueName;
public static final String BYTE_LIST = RepresentationType.BYTE.listName;
public static final String CHARACTER = RepresentationType.CHAR.valueName;
public static final String CHARACTER_LIST = RepresentationType.CHAR.listName;
public static final String SHORT = RepresentationType.SHORT.valueName;
public static final String SHORT_LIST = RepresentationType.SHORT.listName;
public static final String INTEGER = RepresentationType.INTEGER.valueName;
public static final String INTEGER_LIST = RepresentationType.INTEGER.listName;
public static final String LONG = RepresentationType.LONG.valueName;
public static final String LONG_LIST = RepresentationType.LONG.listName;
public static final String FLOAT = RepresentationType.FLOAT.valueName;
public static final String FLOAT_LIST = RepresentationType.FLOAT.listName;
public static final String DOUBLE = RepresentationType.DOUBLE.valueName;
public static final String DOUBLE_LIST = RepresentationType.DOUBLE.listName;
public static final String BOOLEAN = RepresentationType.BOOLEAN.valueName;
public static final String BOOLEAN_LIST = RepresentationType.BOOLEAN.listName;
public static final String EXCEPTION = RepresentationType.EXCEPTION.valueName;
public static final String MAP = RepresentationType.MAP.valueName;
final RepresentationType type;
Representation( RepresentationType type )
{
this.type = type;
}
Representation( String type )
{
this.type = new RepresentationType( type );
}
public RepresentationType getRepresentationType()
{
return this.type;
}
abstract String serialize( RepresentationFormat format, URI baseUri, ExtensionInjector extensions );
abstract void addTo( ListSerializer serializer );
abstract void putTo( MappingSerializer serializer, String key );
boolean isEmpty()
{
return false;
}
public static Representation emptyRepresentation()
{
return new Representation( (RepresentationType) null )
{
@Override
boolean isEmpty()
{
return true;
}
@Override
String serialize( RepresentationFormat format, URI baseUri, ExtensionInjector extensions )
{
return "";
}
@Override
void putTo( MappingSerializer serializer, String key )
{
}
@Override
void addTo( ListSerializer serializer )
{
}
};
}
}
| false
|
community_server-api_src_main_java_org_neo4j_server_rest_repr_Representation.java
|
2,893
|
public class RelationshipRepresentationTest
{
@Test
public void shouldHaveSelfLink() throws BadInputException
{
assertUriMatches( RELATIONSHIP_URI_PATTERN, relrep( 1234 ).selfUri() );
}
@Test
public void shouldHaveType()
{
assertNotNull( relrep( 1234 ).getType() );
}
@Test
public void shouldHaveStartNodeLink() throws BadInputException
{
assertUriMatches( NODE_URI_PATTERN, relrep( 1234 ).startNodeUri() );
}
@Test
public void shouldHaveEndNodeLink() throws BadInputException
{
assertUriMatches( NODE_URI_PATTERN, relrep( 1234 ).endNodeUri() );
}
@Test
public void shouldHavePropertiesLink() throws BadInputException
{
assertUriMatches( RELATIONSHIP_URI_PATTERN + "/properties", relrep( 1234 ).propertiesUri() );
}
@Test
public void shouldHavePropertyLinkTemplate() throws BadInputException
{
assertUriMatches( RELATIONSHIP_URI_PATTERN + "/properties/\\{key\\}", relrep( 1234 ).propertyUriTemplate() );
}
@Test
public void shouldSerialiseToMap()
{
Map<String, Object> repr = serialize( relrep( 1234 ) );
assertNotNull( repr );
verifySerialisation( repr );
}
private RelationshipRepresentation relrep( long id )
{
return new RelationshipRepresentation(
relationship( id, node( 0, properties() ), "LOVES", node( 1, properties() ) ) );
}
public static void verifySerialisation( Map<String, Object> relrep )
{
assertUriMatches( RELATIONSHIP_URI_PATTERN, relrep.get( "self" )
.toString() );
assertUriMatches( NODE_URI_PATTERN, relrep.get( "start" )
.toString() );
assertUriMatches( NODE_URI_PATTERN, relrep.get( "end" )
.toString() );
assertNotNull( relrep.get( "type" ) );
assertUriMatches( RELATIONSHIP_URI_PATTERN + "/properties", relrep.get( "properties" )
.toString() );
assertUriMatches( RELATIONSHIP_URI_PATTERN + "/properties/\\{key\\}", (String) relrep.get( "property" ) );
assertNotNull( relrep.get( "data" ) );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_repr_RelationshipRepresentationTest.java
|
2,894
|
{
@Override
protected Representation underlyingObjectToObject( Relationship relationship )
{
return new RelationshipRepresentation( relationship );
}
} );
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_RelationshipRepresentation.java
|
2,895
|
public final class RelationshipRepresentation extends ObjectRepresentation implements ExtensibleRepresentation,
EntityRepresentation
{
private final Relationship rel;
public RelationshipRepresentation( Relationship rel )
{
super( RepresentationType.RELATIONSHIP );
this.rel = rel;
}
@Override
public String getIdentity()
{
return Long.toString( rel.getId() );
}
public long getId()
{
return rel.getId();
}
@Mapping( "self" )
public ValueRepresentation selfUri()
{
return ValueRepresentation.uri( path( "" ) );
}
private String path( String path )
{
return "relationship/" + rel.getId() + path;
}
static String path( Relationship rel )
{
return "relationship/" + rel.getId();
}
@Mapping( "type" )
public ValueRepresentation getType()
{
return ValueRepresentation.relationshipType( rel.getType() );
}
@Mapping( "start" )
public ValueRepresentation startNodeUri()
{
return ValueRepresentation.uri( NodeRepresentation.path( rel.getStartNode() ) );
}
@Mapping( "end" )
public ValueRepresentation endNodeUri()
{
return ValueRepresentation.uri( NodeRepresentation.path( rel.getEndNode() ) );
}
@Mapping( "properties" )
public ValueRepresentation propertiesUri()
{
return ValueRepresentation.uri( path( "/properties" ) );
}
@Mapping( "property" )
public ValueRepresentation propertyUriTemplate()
{
return ValueRepresentation.template( path( "/properties/{key}" ) );
}
@Override
void extraData( MappingSerializer serializer )
{
MappingWriter properties = serializer.writer.newMapping( RepresentationType.PROPERTIES, "data" );
new PropertiesRepresentation( rel ).serialize( properties );
properties.done();
}
public static ListRepresentation list( Iterable<Relationship> relationships )
{
return new ListRepresentation( RepresentationType.RELATIONSHIP,
new IterableWrapper<Representation, Relationship>( relationships )
{
@Override
protected Representation underlyingObjectToObject( Relationship relationship )
{
return new RelationshipRepresentation( relationship );
}
} );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_RelationshipRepresentation.java
|
2,896
|
public class RelationshipIndexRootRepresentation extends MappingRepresentation
{
private IndexManager indexManager;
public RelationshipIndexRootRepresentation( IndexManager indexManager )
{
super( "relationship-index" );
this.indexManager = indexManager;
}
@Override
protected void serialize( MappingSerializer serializer )
{
for ( String indexName : indexManager.relationshipIndexNames() )
{
RelationshipIndex index = indexManager.forRelationships( indexName );
serializer.putMapping( indexName,
new RelationshipIndexRepresentation( indexName, indexManager.getConfiguration( index ) ) );
}
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_RelationshipIndexRootRepresentation.java
|
2,897
|
public class RelationshipIndexRepresentation extends IndexRepresentation
{
public RelationshipIndexRepresentation( String name )
{
this( name, Collections.EMPTY_MAP );
}
public RelationshipIndexRepresentation( String name, Map<String, String> config )
{
super( name, config );
}
public String propertyContainerType()
{
return "relationship";
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_RelationshipIndexRepresentation.java
|
2,898
|
public class RelationshipAutoIndexRepresentation extends IndexRepresentation {
public RelationshipAutoIndexRepresentation() {
super("", Collections.EMPTY_MAP);
}
@Override
protected String path()
{
return RestfulGraphDatabase.PATH_AUTO_INDEX.replace("{type}", RestfulGraphDatabase.RELATIONSHIP_AUTO_INDEX_TYPE) + "/";
}
@Override
protected String propertyContainerType() {
return null;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_RelationshipAutoIndexRepresentation.java
|
2,899
|
public class PropertiesRepresentationTest
{
@Test
public void shouldContainAddedPropertiesWhenCreatedFromPropertyContainer()
{
Map<String, Object> values = new HashMap<String, Object>();
values.put( "foo", "bar" );
Map<String, Object> serialized = serialize( new PropertiesRepresentation( container( values ) ) );
assertEquals( "bar", serialized.get( "foo" ) );
}
@Test
public void shouldSerializeToMapWithSamePropertiesWhenCreatedFromPropertyContainer()
{
Map<String, Object> values = new HashMap<String, Object>();
values.put( "foo", "bar" );
PropertiesRepresentation properties = new PropertiesRepresentation( container( values ) );
Map<String, Object> map = serialize( properties );
assertEquals( values, map );
}
@Test
public void shouldSerializeToMap()
{
Map<String, Object> values = new HashMap<String, Object>();
values.put( "string", "value" );
values.put( "int", 5 );
values.put( "long", 17L );
values.put( "double", 3.14 );
values.put( "float", 42.0f );
values.put( "string array", new String[] { "one", "two" } );
values.put( "long array", new long[] { 5L, 17L } );
values.put( "double array", new double[] { 3.14, 42.0 } );
PropertiesRepresentation properties = new PropertiesRepresentation( container( values ) );
Map<String, Object> map = serialize( properties );
assertEquals( "value", map.get( "string" ) );
assertEquals( 5, ( (Number) map.get( "int" ) ).longValue() );
assertEquals( 17, ( (Number) map.get( "long" ) ).longValue() );
assertEquals( 3.14, ( (Number) map.get( "double" ) ).doubleValue(), 0.0 );
assertEquals( 42.0, ( (Number) map.get( "float" ) ).doubleValue(), 0.0 );
assertEqualContent( Arrays.asList( "one", "two" ), (List) map.get( "string array" ) );
assertEqualContent( Arrays.asList( 5L, 17L ), (List) map.get( "long array" ) );
assertEqualContent( Arrays.asList( 3.14, 42.0 ), (List) map.get( "double array" ) );
}
@Test
public void shouldBeAbleToSignalEmptiness()
{
PropertiesRepresentation properties = new PropertiesRepresentation( container( new HashMap<String, Object>() ) );
Map<String, Object> values = new HashMap<String, Object>();
values.put( "key", "value" );
assertTrue( properties.isEmpty() );
properties = new PropertiesRepresentation( container( values ) );
assertFalse( properties.isEmpty() );
}
private void assertEqualContent( List<?> expected, List<?> actual )
{
assertEquals( expected.size(), actual.size() );
for ( Iterator<?> ex = expected.iterator(), ac = actual.iterator(); ex.hasNext() && ac.hasNext(); )
{
assertEquals( ex.next(), ac.next() );
}
}
static PropertyContainer container( Map<String, Object> values )
{
PropertyContainer container = mock( PropertyContainer.class );
when( container.getPropertyKeys() ).thenReturn( values.keySet() );
for ( Map.Entry<String, Object> entry : values.entrySet() )
{
when( container.getProperty( entry.getKey(), null ) ).thenReturn( entry.getValue() );
}
return container;
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_repr_PropertiesRepresentationTest.java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.