Unnamed: 0
int64 0
6.7k
| func
stringlengths 12
89.6k
| target
bool 2
classes | project
stringlengths 45
151
|
|---|---|---|---|
2,600
|
public class WrappingNeoServerBootstrapperDocIT extends ExclusiveServerTestBase
{
public
@Rule
TestData<RESTDocsGenerator> gen = TestData.producedThrough( RESTDocsGenerator.PRODUCER );
static GraphDatabaseAPI myDb;
@BeforeClass
public static void setup() throws IOException
{
myDb = (GraphDatabaseAPI) new TestGraphDatabaseFactory().newImpermanentDatabase();
}
@AfterClass
public static void teardown()
{
myDb.shutdown();
}
@Test
public void usingWrappingNeoServerBootstrapper()
{
// START SNIPPET: usingWrappingNeoServerBootstrapper
// You provide the database, which must implement GraphDatabaseAPI.
// Both EmbeddedGraphDatabase and HighlyAvailableGraphDatabase do this.
GraphDatabaseAPI graphdb = myDb;
WrappingNeoServerBootstrapper srv;
srv = new WrappingNeoServerBootstrapper( graphdb );
srv.start();
// The server is now running
// until we stop it:
srv.stop();
// END SNIPPET: usingWrappingNeoServerBootstrapper
}
@Test
public void shouldAllowModifyingProperties()
{
// START SNIPPET: customConfiguredWrappingNeoServerBootstrapper
// let the database accept remote neo4j-shell connections
GraphDatabaseAPI graphdb = (GraphDatabaseAPI) new GraphDatabaseFactory()
.newEmbeddedDatabaseBuilder( TargetDirectory.forTest( getClass() ).makeGraphDbDir().getAbsolutePath() )
.setConfig( ShellSettings.remote_shell_enabled, Settings.TRUE )
.newGraphDatabase();
ServerConfigurator config;
config = new ServerConfigurator( graphdb );
// let the server endpoint be on a custom port
config.configuration().setProperty(
Configurator.WEBSERVER_PORT_PROPERTY_KEY, 7575 );
WrappingNeoServerBootstrapper srv;
srv = new WrappingNeoServerBootstrapper( graphdb, config );
srv.start();
// END SNIPPET: customConfiguredWrappingNeoServerBootstrapper
assertEquals( srv.getServer().baseUri().getPort(), 7575 );
String response = gen.get().payload(
"{\"command\" : \"ls\",\"engine\":\"shell\"}" ).expectedStatus(
Status.OK.getStatusCode() ).post(
"http://127.0.0.1:7575/db/manage/server/console/" ).entity();
assertTrue( response.contains( "neo4j-sh (?)$" ) );
srv.stop();
}
@Test
public void shouldAllowShellConsoleWithoutCustomConfig()
{
WrappingNeoServerBootstrapper srv;
srv = new WrappingNeoServerBootstrapper( myDb );
srv.start();
String response = gen.get().payload(
"{\"command\" : \"ls\",\"engine\":\"shell\"}" ).expectedStatus(
Status.OK.getStatusCode() ).post(
"http://127.0.0.1:7474/db/manage/server/console/" ).entity();
assertTrue( response.contains( "neo4j-sh (?)$" ) );
srv.stop();
}
@Test
public void shouldAllowModifyingListenPorts() throws UnknownHostException
{
ServerConfigurator config = new ServerConfigurator( myDb );
String hostAddress = InetAddress.getLocalHost().getHostAddress();
config.configuration().setProperty(
Configurator.WEBSERVER_ADDRESS_PROPERTY_KEY, hostAddress.toString() );
config.configuration().setProperty(
Configurator.WEBSERVER_PORT_PROPERTY_KEY, "8484" );
WrappingNeoServerBootstrapper srv = new WrappingNeoServerBootstrapper( myDb, config );
srv.start();
try
{
gen.get().expectedStatus( Status.OK.getStatusCode() ).get(
format( "http://%s:7474/db/data/", hostAddress ) );
fail();
}
catch ( ClientHandlerException cee )
{
// ok
}
gen.get().expectedStatus( Status.OK.getStatusCode() ).get(
"http://" + hostAddress + ":8484/db/data/" );
srv.stop();
}
@Test
public void shouldResponseAndBeAbleToModifyDb()
{
WrappingNeoServerBootstrapper srv = new WrappingNeoServerBootstrapper( myDb );
srv.start();
long originalNodeNumber = myDb.getDependencyResolver().resolveDependency( JmxKernelExtension.class )
.getSingleManagementBean( Primitives.class ).getNumberOfNodeIdsInUse();
FunctionalTestHelper helper = new FunctionalTestHelper( srv.getServer() );
JaxRsResponse response = new RestRequest().get( helper.dataUri() );
assertEquals( 200, response.getStatus() );
String nodeData = "{\"age\":12}";
response = new RestRequest().post( helper.dataUri() + "node", nodeData );
assertEquals( 201, response.getStatus() );
long newNodeNumber = myDb.getDependencyResolver().resolveDependency( JmxKernelExtension.class )
.getSingleManagementBean( Primitives.class ).getNumberOfNodeIdsInUse();
assertEquals( originalNodeNumber + 1, newNodeNumber );
srv.stop();
// Should be able to still talk to the db
try ( Transaction tx = myDb.beginTx() )
{
assertTrue( myDb.createNode() != null );
}
}
}
| false
|
community_server_src_test_java_org_neo4j_server_WrappingNeoServerBootstrapperDocIT.java
|
2,601
|
@Deprecated
public class WrappingNeoServerBootstrapper extends Bootstrapper
{
private final GraphDatabaseAPI db;
private final Configurator configurator;
/**
* Create an instance with default settings.
*
* @param db
*/
public WrappingNeoServerBootstrapper( GraphDatabaseAPI db )
{
this( db, new ServerConfigurator( db ) );
}
/**
* Create an instance with custom documentation.
* {@link org.neo4j.server.configuration.ServerConfigurator} is written to fit well here, see its'
* documentation.
*
* @param db
* @param configurator
*/
public WrappingNeoServerBootstrapper( GraphDatabaseAPI db, Configurator configurator )
{
this.db = db;
this.configurator = configurator;
}
@Override
protected Configurator createConfigurator( ConsoleLogger log )
{
return configurator;
}
@Override
protected NeoServer createNeoServer() {
return new WrappingNeoServer(db, configurator);
}
}
| false
|
community_server_src_main_java_org_neo4j_server_WrappingNeoServerBootstrapper.java
|
2,602
|
public class IndexRelationshipDocIT extends AbstractRestFunctionalTestBase
{
private static FunctionalTestHelper functionalTestHelper;
private static GraphDbHelper helper;
private static RestRequest request;
private enum MyRelationshipTypes implements RelationshipType
{
KNOWS
}
@BeforeClass
public static void setupServer()
{
functionalTestHelper = new FunctionalTestHelper( server() );
helper = functionalTestHelper.getGraphDbHelper();
request = RestRequest.req();
}
@Before
public void cleanTheDatabase()
{
cleanDatabase();
}
/**
* GET ${org.neo4j.server.rest.web}/index/relationship/
* <p/>
* TODO: could be abstract
*
* @return the Reponse
*/
public JaxRsResponse httpGetIndexRelationshipRoot()
{
return httpGet( functionalTestHelper.relationshipIndexUri() );
}
/**
* POST ${org.neo4j.server.rest.web}/index/relationship {
* "name":"index-name" "config":{ // optional map of index configuration
* params "key1":"value1", "key2":"value2" } }
*
* POST ${org.neo4j.server.rest.web}/index/relationship/{indexName}/{key}/{
* value} "http://uri.for.node.to.index"
*/
@Test
public void shouldCreateANamedRelationshipIndexAndAddToIt() throws JsonParseException
{
String indexName = "favorites";
int expectedIndexes = helper.getRelationshipIndexes().length + 1;
Map<String, String> indexSpecification = new HashMap<>();
indexSpecification.put( "name", indexName );
JaxRsResponse response = httpPostIndexRelationshipRoot( JsonHelper.createJsonFrom( indexSpecification ) );
assertEquals( 201, response.getStatus() );
assertNotNull( response.getHeaders().get( "Location" ).get( 0 ) );
assertEquals( expectedIndexes, helper.getRelationshipIndexes().length );
assertNotNull( helper.createRelationshipIndex( indexName ) );
// Add a relationship to the index
String key = "key";
String value = "value";
String relationshipType = "related-to";
long relationshipId = helper.createRelationship( relationshipType );
response = httpPostIndexRelationshipNameKeyValue( indexName, relationshipId, key, value );
assertEquals( Status.CREATED.getStatusCode(), response.getStatus() );
String indexUri = response.getHeaders().get( "Location" ).get( 0 );
assertNotNull( indexUri );
assertEquals( Arrays.asList( (Long) relationshipId ), helper.getIndexedRelationships( indexName, key, value ) );
// Get the relationship from the indexed URI (Location in header)
response = httpGet( indexUri );
assertEquals( 200, response.getStatus() );
String discovredEntity = response.getEntity();
Map<String, Object> map = JsonHelper.jsonToMap( discovredEntity );
assertNotNull( map.get( "self" ) );
}
private JaxRsResponse httpPostIndexRelationshipRoot( String jsonIndexSpecification )
{
return RestRequest.req().post( functionalTestHelper.relationshipIndexUri(), jsonIndexSpecification );
}
private JaxRsResponse httpGetIndexRelationshipNameKeyValue( String indexName, String key, String value )
{
return RestRequest.req().get( functionalTestHelper.indexRelationshipUri( indexName, key, value ) );
}
private JaxRsResponse httpPostIndexRelationshipNameKeyValue( String indexName, long relationshipId, String key,
String value )
{
return RestRequest.req().post( functionalTestHelper.indexRelationshipUri( indexName ),
createJsonStringFor( relationshipId, key, value ) );
}
private String createJsonStringFor( final long relationshipId, final String key, final String value )
{
return "{\"key\": \"" + key + "\", \"value\": \"" + value + "\", \"uri\": \""
+ functionalTestHelper.relationshipUri( relationshipId ) + "\"}";
}
private JaxRsResponse httpGet( String indexUri )
{
return request.get( indexUri );
}
@Test
public void shouldGet404WhenRequestingIndexUriWhichDoesntExist()
{
String key = "key3";
String value = "value";
String indexName = "nosuchindex";
String indexUri = functionalTestHelper.relationshipIndexUri() + indexName + "/" + key + "/" + value;
JaxRsResponse response = httpGet( indexUri );
assertEquals( Status.NOT_FOUND.getStatusCode(), response.getStatus() );
}
@Test
public void shouldGet404WhenDeletingNonExtistentIndex()
{
String indexName = "nosuchindex";
String indexUri = functionalTestHelper.relationshipIndexUri() + indexName;
JaxRsResponse response = request.delete( indexUri );
assertEquals( Status.NOT_FOUND.getStatusCode(), response.getStatus() );
}
@Test
public void shouldGet200AndArrayOfRelationshipRepsWhenGettingFromIndex() throws PropertyValueException
{
final long startNode = helper.createNode();
final long endNode = helper.createNode();
final String key = "key_get";
final String value = "value";
final String relationshipName1 = "related-to";
final String relationshipName2 = "dislikes";
String jsonString = jsonRelationshipCreationSpecification( relationshipName1, endNode, key, value );
JaxRsResponse createRelationshipResponse = httpPostCreateRelationship( startNode, jsonString );
assertEquals( 201, createRelationshipResponse.getStatus() );
String relationshipLocation1 = createRelationshipResponse.getLocation().toString();
jsonString = jsonRelationshipCreationSpecification( relationshipName2, endNode, key, value );
createRelationshipResponse = httpPostCreateRelationship( startNode, jsonString );
assertEquals( 201, createRelationshipResponse.getStatus() );
String relationshipLocation2 = createRelationshipResponse.getHeaders().get( HttpHeaders.LOCATION ).get( 0 );
String indexName = "matrix";
JaxRsResponse indexCreationResponse = httpPostIndexRelationshipRoot( "{\"name\":\"" + indexName + "\"}" );
assertEquals( 201, indexCreationResponse.getStatus() );
JaxRsResponse indexedRelationshipResponse = httpPostIndexRelationshipNameKeyValue( indexName,
functionalTestHelper.getRelationshipIdFromUri( relationshipLocation1 ), key, value );
String indexLocation1 = indexedRelationshipResponse.getHeaders().get( HttpHeaders.LOCATION ).get( 0 );
indexedRelationshipResponse = httpPostIndexRelationshipNameKeyValue( indexName,
functionalTestHelper.getRelationshipIdFromUri( relationshipLocation2 ), key, value );
String indexLocation2 = indexedRelationshipResponse.getHeaders().get( HttpHeaders.LOCATION ).get( 0 );
Map<String, String> uriToName = new HashMap<>();
uriToName.put( indexLocation1.toString(), relationshipName1 );
uriToName.put( indexLocation2.toString(), relationshipName2 );
JaxRsResponse response = RestRequest.req().get(
functionalTestHelper.indexRelationshipUri( indexName, key, value ) );
assertEquals( 200, response.getStatus() );
Collection<?> items = (Collection<?>) JsonHelper.jsonToSingleValue( response.getEntity() );
int counter = 0;
for ( Object item : items )
{
Map<?, ?> map = (Map<?, ?>) item;
assertNotNull( map.get( "self" ) );
String indexedUri = (String) map.get( "indexed" );
assertEquals( uriToName.get( indexedUri ), map.get( "type" ) );
counter++;
}
assertEquals( 2, counter );
response.close();
}
private JaxRsResponse httpPostCreateRelationship( long startNode, String jsonString )
{
return RestRequest.req().post( functionalTestHelper.dataUri() + "node/" + startNode + "/relationships",
jsonString );
}
private String jsonRelationshipCreationSpecification( String relationshipName, long endNode, String key,
String value )
{
return "{\"to\" : \"" + functionalTestHelper.dataUri() + "node/" + endNode + "\"," + "\"type\" : \""
+ relationshipName + "\", " + "\"data\" : {\"" + key + "\" : \"" + value + "\"}}";
}
@Test
public void shouldGet200WhenGettingRelationshipFromIndexWithNoHits()
{
String indexName = "empty-index";
helper.createRelationshipIndex( indexName );
JaxRsResponse response = RestRequest.req().get(
functionalTestHelper.indexRelationshipUri( indexName, "non-existent-key", "non-existent-value" ) );
assertEquals( 200, response.getStatus() );
}
@Test
public void shouldGet200WhenQueryingIndex()
{
String indexName = "bobTheIndex";
String key = "bobsKey";
String value = "bobsValue";
long relationship = helper.createRelationship( "TYPE" );
helper.addRelationshipToIndex( indexName, key, value, relationship );
JaxRsResponse response = RestRequest.req().get(
functionalTestHelper.indexRelationshipUri( indexName ) + "?query=" + key + ":" + value );
assertEquals( 200, response.getStatus() );
}
@Test
public void shouldBeAbleToRemoveIndexing()
{
String key1 = "kvkey1";
String key2 = "kvkey2";
String value1 = "value1";
String value2 = "value2";
String indexName = "kvrel";
long relationship = helper.createRelationship( "some type" );
helper.setRelationshipProperties( relationship,
MapUtil.map( key1, value1, key1, value2, key2, value1, key2, value2 ) );
helper.addRelationshipToIndex( indexName, key1, value1, relationship );
helper.addRelationshipToIndex( indexName, key1, value2, relationship );
helper.addRelationshipToIndex( indexName, key2, value1, relationship );
helper.addRelationshipToIndex( indexName, key2, value2, relationship );
assertEquals( 1, helper.getIndexedRelationships( indexName, key1, value1 ).size() );
assertEquals( 1, helper.getIndexedRelationships( indexName, key1, value2 ).size() );
assertEquals( 1, helper.getIndexedRelationships( indexName, key2, value1 ).size() );
assertEquals( 1, helper.getIndexedRelationships( indexName, key2, value2 ).size() );
JaxRsResponse response = RestRequest.req().delete(
functionalTestHelper.relationshipIndexUri() + indexName + "/" + key1 + "/" + value1 + "/"
+ relationship );
assertEquals( 204, response.getStatus() );
assertEquals( 0, helper.getIndexedRelationships( indexName, key1, value1 ).size() );
assertEquals( 1, helper.getIndexedRelationships( indexName, key1, value2 ).size() );
assertEquals( 1, helper.getIndexedRelationships( indexName, key2, value1 ).size() );
assertEquals( 1, helper.getIndexedRelationships( indexName, key2, value2 ).size() );
response = RestRequest.req().delete(
functionalTestHelper.relationshipIndexUri() + indexName + "/" + key2 + "/" + relationship );
assertEquals( 204, response.getStatus() );
assertEquals( 0, helper.getIndexedRelationships( indexName, key1, value1 ).size() );
assertEquals( 1, helper.getIndexedRelationships( indexName, key1, value2 ).size() );
assertEquals( 0, helper.getIndexedRelationships( indexName, key2, value1 ).size() );
assertEquals( 0, helper.getIndexedRelationships( indexName, key2, value2 ).size() );
response = RestRequest.req().delete(
functionalTestHelper.relationshipIndexUri() + indexName + "/" + relationship );
assertEquals( 204, response.getStatus() );
assertEquals( 0, helper.getIndexedRelationships( indexName, key1, value1 ).size() );
assertEquals( 0, helper.getIndexedRelationships( indexName, key1, value2 ).size() );
assertEquals( 0, helper.getIndexedRelationships( indexName, key2, value1 ).size() );
assertEquals( 0, helper.getIndexedRelationships( indexName, key2, value2 ).size() );
// Delete the index
response = RestRequest.req().delete( functionalTestHelper.indexRelationshipUri( indexName ) );
assertEquals( 204, response.getStatus() );
assertFalse( asList( helper.getRelationshipIndexes() ).contains( indexName ) );
}
@Test
public void shouldBeAbleToIndexValuesContainingSpaces() throws Exception
{
final long startNodeId = helper.createNode();
final long endNodeId = helper.createNode();
final String relationshiptype = "tested-together";
final long relationshipId = helper.createRelationship( relationshiptype, startNodeId, endNodeId );
final String key = "key";
final String value = "value with spaces in it";
final String indexName = "spacey-values";
helper.createRelationshipIndex( indexName );
JaxRsResponse response = httpPostIndexRelationshipNameKeyValue( indexName, relationshipId, key, value );
assertEquals( Status.CREATED.getStatusCode(), response.getStatus() );
URI location = response.getLocation();
response.close();
response = httpGetIndexRelationshipNameKeyValue( indexName, key, URIHelper.encode( value ) );
assertEquals( Status.OK.getStatusCode(), response.getStatus() );
String responseEntity = response.getEntity();
Collection<?> hits = (Collection<?>) JsonHelper.jsonToSingleValue( responseEntity );
assertEquals( 1, hits.size() );
response.close();
CLIENT.resource( location ).delete();
response = httpGetIndexRelationshipNameKeyValue( indexName, key, URIHelper.encode( value ) );
assertEquals( 200, response.getStatus() );
responseEntity = response.getEntity();
hits = (Collection<?>) JsonHelper.jsonToSingleValue( responseEntity );
assertEquals( 0, hits.size() );
response.close();
}
@Test
public void shouldRespondWith400WhenSendingCorruptJson() throws Exception
{
final String indexName = "botherable-index";
helper.createRelationshipIndex( indexName );
final String corruptJson = "{[}";
JaxRsResponse response = RestRequest.req().post( functionalTestHelper.indexRelationshipUri( indexName ),
corruptJson );
assertEquals( 400, response.getStatus() );
}
/**
* Get or create unique relationship (create).
*
* Create a unique relationship in an index.
* If a relationship matching the given key and value already exists in the index, it will be returned.
* If not, a new relationship will be created.
*
* NOTE: The type and direction of the relationship is not regarded when determining uniqueness.
*/
@Documented
@Test
public void get_or_create_relationship() throws Exception
{
final String index = "MyIndex", type="knowledge", key = "name", value = "Tobias";
helper.createRelationshipIndex( index );
long start = helper.createNode();
long end = helper.createNode();
gen.get()
.noGraph()
.expectedStatus( 201 /* created */)
.payloadType( MediaType.APPLICATION_JSON_TYPE )
.payload( "{\"key\": \"" + key + "\", \"value\":\"" + value +
"\", \"start\": \"" + functionalTestHelper.nodeUri( start ) +
"\", \"end\": \"" + functionalTestHelper.nodeUri( end ) +
"\", \"type\": \"" + type + "\"}" )
.post( functionalTestHelper.relationshipIndexUri() + index + "/?uniqueness=get_or_create" );
}
/**
* Get or create unique relationship (existing).
*
* Here, in case
* of an already existing relationship, the sent data is ignored and the
* existing relationship returned.
*/
@Documented
@Test
public void get_or_create_unique_relationship_existing() throws Exception
{
final String index = "rels", key = "name", value = "Peter";
GraphDatabaseService graphdb = graphdb();
helper.createRelationshipIndex( index );
try ( Transaction tx = graphdb.beginTx() )
{
Node node1 = graphdb.createNode();
Node node2 = graphdb.createNode();
Relationship rel = node1.createRelationshipTo( node2, MyRelationshipTypes.KNOWS );
graphdb.index().forRelationships( index ).add( rel, key, value );
tx.success();
}
gen.get()
.noGraph()
.expectedStatus( 200 /* existing */)
.payloadType( MediaType.APPLICATION_JSON_TYPE )
.payload(
"{\"key\": \"" + key + "\", \"value\": \"" + value + "\", \"start\": \""
+ functionalTestHelper.nodeUri( helper.createNode() ) + "\", \"end\": \""
+ functionalTestHelper.nodeUri( helper.createNode() ) + "\", \"type\":\""
+ MyRelationshipTypes.KNOWS + "\"}" )
.post( functionalTestHelper.relationshipIndexUri() + index + "?uniqueness=get_or_create" );
}
/**
* Create a unique relationship or return fail (create).
*
* Here, in case
* of an already existing relationship, an error should be returned. In this
* example, no existing relationship is found and a new relationship is created.
*/
@Documented
@Test
public void create_a_unique_relationship_or_return_fail___create() throws Exception
{
final String index = "rels", key = "name", value = "Tobias";
helper.createRelationshipIndex( index );
ResponseEntity response = gen
.get()
.noGraph()
.expectedStatus( 201 /* created */)
.payloadType( MediaType.APPLICATION_JSON_TYPE )
.payload(
"{\"key\": \"" + key + "\", \"value\": \"" + value + "\", \"start\": \""
+ functionalTestHelper.nodeUri( helper.createNode() ) + "\", \"end\": \""
+ functionalTestHelper.nodeUri( helper.createNode() ) + "\", \"type\":\""
+ MyRelationshipTypes.KNOWS + "\"}" )
.post( functionalTestHelper.relationshipIndexUri() + index + "?uniqueness=create_or_fail" );
MultivaluedMap<String, String> headers = response.response().getHeaders();
Map<String, Object> result = JsonHelper.jsonToMap( response.entity() );
assertEquals( result.get( "indexed" ), headers.getFirst( "Location" ) );
}
/**
* Create a unique relationship or return fail (fail).
*
* Here, in case
* of an already existing relationship, an error should be returned. In this
* example, an existing relationship is found and an error is returned.
*/
@Documented
@Test
public void create_a_unique_relationship_or_return_fail___fail() throws Exception
{
final String index = "rels", key = "name", value = "Peter";
GraphDatabaseService graphdb = graphdb();
helper.createRelationshipIndex( index );
try ( Transaction tx = graphdb.beginTx() )
{
Node node1 = graphdb.createNode();
Node node2 = graphdb.createNode();
Relationship rel = node1.createRelationshipTo( node2, MyRelationshipTypes.KNOWS );
graphdb.index().forRelationships( index ).add( rel, key, value );
tx.success();
}
gen.get()
.noGraph()
.expectedStatus( 409 /* conflict */)
.payloadType( MediaType.APPLICATION_JSON_TYPE )
.payload(
"{\"key\": \"" + key + "\", \"value\": \"" + value + "\", \"start\": \""
+ functionalTestHelper.nodeUri( helper.createNode() ) + "\", \"end\": \""
+ functionalTestHelper.nodeUri( helper.createNode() ) + "\", \"type\":\""
+ MyRelationshipTypes.KNOWS + "\"}" )
.post( functionalTestHelper.relationshipIndexUri() + index + "?uniqueness=create_or_fail" );
}
/**
* Add an existing relationship to a unique index (not indexed).
*
* If a relationship matching the given key and value already exists in the index, it will be returned.
* If not, an `HTTP 409` (conflict) status will be returned in this case, as we are using `create_or_fail`.
*
* It's possible to use `get_or_create` uniqueness as well.
*
* NOTE: The type and direction of the relationship is not regarded when determining uniqueness.
*/
@Documented
@Test
public void put_relationship_or_fail_if_absent() throws Exception
{
final String index = "rels", key = "name", value = "Peter";
helper.createRelationshipIndex( index );
gen.get()
.noGraph()
.expectedStatus( 201 /* created */)
.payloadType( MediaType.APPLICATION_JSON_TYPE )
.payload(
"{\"key\": \""
+ key
+ "\", \"value\": \""
+ value
+ "\", \"uri\":\""
+ functionalTestHelper.relationshipUri( helper.createRelationship( "KNOWS",
helper.createNode(), helper.createNode() ) ) + "\"}" )
.post( functionalTestHelper.relationshipIndexUri() + index + "?uniqueness=create_or_fail" );
}
/**
* Add an existing relationship to a unique index (already indexed).
*/
@Documented
@Test
public void put_relationship_if_absent_only_fail() throws Exception
{
// Given
final String index = "rels", key = "name", value = "Peter";
GraphDatabaseService graphdb = graphdb();
helper.createRelationshipIndex( index );
try ( Transaction tx = graphdb.beginTx() )
{
Node node1 = graphdb.createNode();
Node node2 = graphdb.createNode();
Relationship rel = node1.createRelationshipTo( node2, MyRelationshipTypes.KNOWS );
graphdb.index().forRelationships( index ).add( rel, key, value );
tx.success();
}
Relationship rel;
try ( Transaction tx = graphdb.beginTx() )
{
Node node1 = graphdb.createNode();
Node node2 = graphdb.createNode();
rel = node1.createRelationshipTo( node2, MyRelationshipTypes.KNOWS );
tx.success();
}
// When & Then
gen.get()
.noGraph()
.expectedStatus( 409 /* conflict */)
.payloadType( MediaType.APPLICATION_JSON_TYPE )
.payload(
"{\"key\": \"" + key + "\", \"value\": \"" + value + "\", \"uri\":\""
+ functionalTestHelper.relationshipUri( rel.getId() ) + "\"}" )
.post( functionalTestHelper.relationshipIndexUri() + index + "?uniqueness=create_or_fail" );
}
@Test
public void already_indexed_relationship_should_not_fail_on_create_or_fail() throws Exception
{
// Given
final String index = "rels", key = "name", value = "Peter";
GraphDatabaseService graphdb = graphdb();
helper.createRelationshipIndex( index );
Relationship rel;
try ( Transaction tx = graphdb.beginTx() )
{
Node node1 = graphdb.createNode();
Node node2 = graphdb.createNode();
rel = node1.createRelationshipTo( node2, MyRelationshipTypes.KNOWS );
graphdb.index().forRelationships( index ).add( rel, key, value );
tx.success();
}
// When & Then
gen.get()
.noGraph()
.expectedStatus( 201 )
.payloadType( MediaType.APPLICATION_JSON_TYPE )
.payload(
"{\"key\": \"" + key + "\", \"value\": \"" + value + "\", \"uri\":\""
+ functionalTestHelper.relationshipUri( rel.getId() ) + "\"}" )
.post( functionalTestHelper.relationshipIndexUri() + index + "?uniqueness=create_or_fail" );
}
/**
* This can be safely removed in version 1.11 an onwards.
*/
@Test
public void createUniqueShouldBeBackwardsCompatibleWith1_8() throws Exception
{
final String index = "rels", key = "name", value = "Peter";
GraphDatabaseService graphdb = graphdb();
helper.createRelationshipIndex( index );
try ( Transaction tx = graphdb.beginTx() )
{
Node node1 = graphdb.createNode();
Node node2 = graphdb.createNode();
Relationship rel = node1.createRelationshipTo( node2, MyRelationshipTypes.KNOWS );
graphdb.index().forRelationships( index ).add( rel, key, value );
tx.success();
}
gen.get()
.noGraph()
.expectedStatus( 200 /* conflict */)
.payloadType( MediaType.APPLICATION_JSON_TYPE )
.payload(
"{\"key\": \"" + key + "\", \"value\": \"" + value + "\", \"start\": \""
+ functionalTestHelper.nodeUri( helper.createNode() ) + "\", \"end\": \""
+ functionalTestHelper.nodeUri( helper.createNode() ) + "\", \"type\":\""
+ MyRelationshipTypes.KNOWS + "\"}" )
.post( functionalTestHelper.relationshipIndexUri() + index + "?unique" );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_IndexRelationshipDocIT.java
|
2,603
|
public class JaxRsResponse extends Response
{
private final int status;
private final MultivaluedMap<String,Object> metaData;
private final MultivaluedMap<String, String> headers;
private final URI location;
private String data;
private MediaType type;
public JaxRsResponse( ClientResponse response )
{
this(response, extractContent(response));
}
private static String extractContent(ClientResponse response) {
if (response.getStatus() == Status.NO_CONTENT.getStatusCode()) return null;
return response.getEntity(String.class);
}
public JaxRsResponse(ClientResponse response, String entity) {
status = response.getStatus();
metaData = extractMetaData(response);
headers = extractHeaders(response);
location = response.getLocation();
type = response.getType();
data = entity;
response.close();
}
@Override
public String getEntity()
{
return data;
}
@Override
public int getStatus()
{
return status;
}
@Override
public MultivaluedMap<String, Object> getMetadata()
{
return metaData;
}
private MultivaluedMap<String, Object> extractMetaData(ClientResponse jettyResponse) {
MultivaluedMap<String, Object> metadata = new StringKeyObjectValueIgnoreCaseMultivaluedMap();
for ( Map.Entry<String, List<String>> header : jettyResponse.getHeaders()
.entrySet() )
{
for ( Object value : header.getValue() )
{
metadata.putSingle( header.getKey(), value );
}
}
return metadata;
}
public MultivaluedMap<String, String> getHeaders()
{
return headers;
}
private MultivaluedMap<String, String> extractHeaders(ClientResponse jettyResponse) {
return jettyResponse.getHeaders();
}
// new URI( getHeaders().get( HttpHeaders.LOCATION ).get(0));
public URI getLocation()
{
return location;
}
public void close()
{
}
public static JaxRsResponse extractFrom(ClientResponse clientResponse) {
return new JaxRsResponse(clientResponse);
}
public MediaType getType() {
return type;
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_JaxRsResponse.java
|
2,604
|
public class RestfulGraphDatabasePagedTraversalTest
{
private static final String BASE_URI = "http://neo4j.org:7474/";
private RestfulGraphDatabase service;
private Database database;
private EntityOutputFormat output;
private GraphDbHelper helper;
private LeaseManager leaseManager;
private AbstractGraphDatabase graph;
@Before
public void startDatabase() throws IOException
{
graph = (AbstractGraphDatabase)new TestGraphDatabaseFactory().newImpermanentDatabase();
database = new WrappedDatabase(graph);
helper = new GraphDbHelper( database );
output = new EntityOutputFormat( new JsonFormat(), URI.create( BASE_URI ), null );
leaseManager = new LeaseManager( new FakeClock() );
service = new RestfulGraphDatabase( new JsonFormat(), output,
new DatabaseActions( leaseManager, ForceMode.forced, true, database.getGraph() ) );
service = new TransactionWrappingRestfulGraphDatabase( graph, service );
}
@After
public void shutdownDatabase() throws Throwable
{
this.graph.shutdown();
}
@Test
public void shouldLodgeAPagingTraverserAndTraverseTheFirstPageBeforeRespondingWith201()
{
Response response = createAPagedTraverser();
assertEquals( 201, response.getStatus() );
String responseUri = response.getMetadata()
.get( "Location" )
.get( 0 )
.toString();
assertThat( responseUri, containsString( "/node/0/paged/traverse/node/" ) );
assertNotNull( response.getEntity() );
assertThat( new String( (byte[]) response.getEntity() ), containsString( "\"name\" : \"19\"" ) );
}
@Test
public void givenAPageTraversalHasBeenCreatedShouldYieldNextPageAndRespondWith200() throws Exception
{
Response response = createAPagedTraverser();
String traverserId = parseTraverserIdFromLocationUri( response );
response = service.pagedTraverse( traverserId, TraverserReturnType.node );
assertEquals( 200, response.getStatus() );
assertNotNull( response.getEntity() );
assertThat( new String( (byte[]) response.getEntity() ), not( containsString( "\"name\" : \"19\"" ) ) );
assertThat( new String( (byte[]) response.getEntity() ), containsString( "\"name\" : \"91\"" ) );
}
@Test
public void shouldRespondWith404WhenNoSuchTraversalRegistered()
{
Response response = service.pagedTraverse( "anUnlikelyTraverserId", TraverserReturnType.node );
assertEquals( 404, response.getStatus() );
}
@Test
public void shouldRespondWith404WhenTraversalHasExpired()
{
Response response = createAPagedTraverser();
((FakeClock) leaseManager.getClock()).forward( 2, TimeUnit.MINUTES);
String traverserId = parseTraverserIdFromLocationUri( response );
response = service.pagedTraverse( traverserId, TraverserReturnType.node );
assertEquals( 404, response.getStatus() );
}
@Test
public void shouldRenewLeaseAtEachTraversal()
{
Response response = createAPagedTraverser();
String traverserId = parseTraverserIdFromLocationUri( response );
((FakeClock) leaseManager.getClock()).forward( 30, TimeUnit.SECONDS );
response = service.pagedTraverse( traverserId, TraverserReturnType.node );
assertEquals( 200, response.getStatus() );
((FakeClock) leaseManager.getClock()).forward( 30, TimeUnit.SECONDS );
response = service.pagedTraverse( traverserId, TraverserReturnType.node );
assertEquals( 200, response.getStatus() );
((FakeClock) leaseManager.getClock()).forward( enoughMinutesToExpireTheLease(), TimeUnit.MINUTES );
response = service.pagedTraverse( traverserId, TraverserReturnType.node );
assertEquals( 404, response.getStatus() );
}
private int enoughMinutesToExpireTheLease()
{
return 10;
}
private Response createAPagedTraverser()
{
long startNodeId = createListOfNodes( 1000 );
String description = "{"
+ "\"prune_evaluator\":{\"language\":\"builtin\",\"name\":\"none\"},"
+ "\"return_filter\":{\"language\":\"javascript\",\"body\":\"position.endNode().getProperty('name')" +
".contains('9');\"},"
+ "\"order\":\"depth first\","
+ "\"relationships\":{\"type\":\"PRECEDES\",\"direction\":\"out\"}" + "}";
final int SIXTY_SECONDS = 60;
final int PAGE_SIZE = 10;
return service.createPagedTraverser( startNodeId, TraverserReturnType.node, PAGE_SIZE,
SIXTY_SECONDS, description );
}
private long createListOfNodes( int numberOfNodes )
{
Transaction tx = database.getGraph().beginTx();
try
{
long zerothNode = helper.createNode( MapUtil.map( "name", String.valueOf( 0 ) ) );
long previousNodeId = zerothNode;
for ( int i = 1; i < numberOfNodes; i++ )
{
long currentNodeId = helper.createNode( MapUtil.map( "name", String.valueOf( i ) ) );
database.getGraph().getNodeById( previousNodeId )
.createRelationshipTo( database.getGraph().getNodeById( currentNodeId ),
DynamicRelationshipType.withName( "PRECEDES" ) );
previousNodeId = currentNodeId;
}
tx.success();
return zerothNode;
}
finally
{
tx.finish();
}
}
private String parseTraverserIdFromLocationUri( Response response )
{
String locationUri = response.getMetadata()
.get( "Location" )
.get( 0 )
.toString();
return locationUri.substring( locationUri.lastIndexOf( "/" ) + 1 );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_web_RestfulGraphDatabasePagedTraversalTest.java
|
2,605
|
{
@Override
public void run()
{
// start and block until finish
transactionHandle.execute( statements, mock( ExecutionResultSerializer.class ) );
}
} ).start();
| false
|
community_server_src_test_java_org_neo4j_server_rest_transactional_ConcurrentTransactionAccessTest.java
|
2,606
|
public class ConcurrentTransactionAccessTest
{
@Test
public void shouldThrowSpecificExceptionOnConcurrentTransactionAccess() throws Exception
{
// given
TransactionRegistry registry =
new TransactionHandleRegistry( mock( Clock.class), 0, StringLogger.DEV_NULL );
TransitionalPeriodTransactionMessContainer kernel = mock( TransitionalPeriodTransactionMessContainer.class );
when(kernel.newTransaction()).thenReturn( mock(TransitionalTxManagementKernelTransaction.class) );
TransactionFacade actions = new TransactionFacade( kernel, null, registry, null, null );
final TransactionHandle transactionHandle = actions.newTransactionHandle( new DisgustingUriScheme() );
final DoubleLatch latch = new DoubleLatch();
final StatementDeserializer statements = mock( StatementDeserializer.class );
when( statements.hasNext() ).thenAnswer( new Answer<Boolean>()
{
@Override
public Boolean answer( InvocationOnMock invocation ) throws Throwable
{
latch.startAndAwaitFinish();
return false;
}
} );
new Thread( new Runnable()
{
@Override
public void run()
{
// start and block until finish
transactionHandle.execute( statements, mock( ExecutionResultSerializer.class ) );
}
} ).start();
latch.awaitStart();
try
{
// when
actions.findTransactionHandle( DisgustingUriScheme.parseTxId( transactionHandle.uri() ) );
fail( "should have thrown exception" );
}
catch ( InvalidConcurrentTransactionAccess neo4jError )
{
// then we get here
}
finally
{
latch.finish();
}
}
private static class DisgustingUriScheme implements TransactionUriScheme
{
private static long parseTxId( URI txUri )
{
return parseLong( txUri.toString() );
}
@Override
public URI txUri( long id )
{
return URI.create( String.valueOf( id ) );
}
@Override
public URI txCommitUri( long id )
{
return txUri( id );
}
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_transactional_ConcurrentTransactionAccessTest.java
|
2,607
|
public class CommitOnSuccessfulStatusCodeRepresentationWriteHandler implements RepresentationWriteHandler
{
private final HttpContext httpContext;
private final Transaction transaction;
public CommitOnSuccessfulStatusCodeRepresentationWriteHandler( HttpContext httpContext, Transaction transaction )
{
this.httpContext = httpContext;
this.transaction = transaction;
}
@Override
public void onRepresentationStartWriting()
{
// do nothing
}
@Override
public void onRepresentationWritten()
{
HttpResponseContext response = httpContext.getResponse();
int statusCode = response.getStatus();
if ( statusCode >= 200 && statusCode < 300 )
{
transaction.success();
}
}
@Override
public void onRepresentationFinal()
{
transaction.close();
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_transactional_CommitOnSuccessfulStatusCodeRepresentationWriteHandler.java
|
2,608
|
class AggregatingWriter implements ResultDataContentWriter
{
private final ResultDataContentWriter[] writers;
public AggregatingWriter( ResultDataContentWriter[] writers )
{
this.writers = writers;
}
@Override
public void write( JsonGenerator out, Iterable<String> columns, Map<String, Object> row ) throws IOException
{
for ( ResultDataContentWriter writer : writers )
{
writer.write( out, columns, row );
}
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_transactional_AggregatingWriter.java
|
2,609
|
public class StreamingTraverserDocIT extends TraverserDocIT
{
@Override
public RESTDocsGenerator gen() {
return super.gen().noDoc().withHeader(StreamingJsonFormat.STREAM_HEADER, "true");
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_streaming_StreamingTraverserDocIT.java
|
2,610
|
public class StreamingRelationshipDocIT extends RelationshipDocIT
{
@Override
public RESTDocsGenerator gen() {
return super.gen().noDoc().withHeader(StreamingJsonFormat.STREAM_HEADER, "true");
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_streaming_StreamingRelationshipDocIT.java
|
2,611
|
public class StreamingPathsDocIT extends PathsDocIT
{
@Override
public RESTDocsGenerator gen() {
return super.gen().noDoc().withHeader(StreamingJsonFormat.STREAM_HEADER, "true");
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_streaming_StreamingPathsDocIT.java
|
2,612
|
public class StreamingIndexNodeDocIT extends IndexNodeDocIT
{
@Override
public RESTDocsGenerator gen() {
return super.gen().noDoc().withHeader(StreamingJsonFormat.STREAM_HEADER, "true");
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_streaming_StreamingIndexNodeDocIT.java
|
2,613
|
public class StreamingCypherDocIT extends CypherDocIT
{
@Override
public RESTDocsGenerator gen() {
return super.gen().noDoc().withHeader(StreamingJsonFormat.STREAM_HEADER, "true");
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_streaming_StreamingCypherDocIT.java
|
2,614
|
public class StreamingBatchOperationDocIT extends AbstractRestFunctionalTestBase
{
/**
* By specifying an extended header attribute in the HTTP request,
* the server will stream the results back as soon as they are processed on the server side
* instead of constructing a full response when all entities are processed.
*/
@SuppressWarnings( "unchecked" )
@Test
@Graph("Joe knows John")
public void execute_multiple_operations_in_batch_streaming() throws Exception {
long idJoe = data.get().get( "Joe" ).getId();
String jsonString = new PrettyJSON()
.array()
.object()
.key("method") .value("PUT")
.key("to") .value("/node/" + idJoe + "/properties")
.key("body")
.object()
.key("age").value(1)
.endObject()
.key("id") .value(0)
.endObject()
.object()
.key("method") .value("GET")
.key("to") .value("/node/" + idJoe)
.key("id") .value(1)
.endObject()
.object()
.key("method") .value("POST")
.key("to") .value("/node")
.key("body")
.object()
.key("age").value(1)
.endObject()
.key("id") .value(2)
.endObject()
.object()
.key("method") .value("POST")
.key("to") .value("/node")
.key("body")
.object()
.key("age").value(1)
.endObject()
.key("id") .value(3)
.endObject()
.endArray().toString();
String entity = gen.get()
.expectedType( APPLICATION_JSON_TYPE )
.withHeader(StreamingFormat.STREAM_HEADER,"true")
.payload(jsonString)
.expectedStatus(200)
.post( batchUri() ).entity();
List<Map<String, Object>> results = JsonHelper.jsonToList(entity);
assertEquals(4, results.size());
Map<String, Object> putResult = results.get(0);
Map<String, Object> getResult = results.get(1);
Map<String, Object> firstPostResult = results.get(2);
Map<String, Object> secondPostResult = results.get(3);
// Ids should be ok
assertEquals(0, putResult.get("id"));
assertEquals(2, firstPostResult.get("id"));
assertEquals(3, secondPostResult.get("id"));
// Should contain "from"
assertEquals("/node/"+idJoe+"/properties", putResult.get("from"));
assertEquals("/node/"+idJoe, getResult.get("from"));
assertEquals("/node", firstPostResult.get("from"));
assertEquals("/node", secondPostResult.get("from"));
// Post should contain location
assertTrue(((String) firstPostResult.get("location")).length() > 0);
assertTrue(((String) secondPostResult.get("location")).length() > 0);
// Should have created by the first PUT request
Map<String, Object> body = (Map<String, Object>) getResult.get("body");
assertEquals(1, ((Map<String, Object>) body.get("data")).get("age"));
}
/**
* The batch operation API allows you to refer to the URI returned from a
* created resource in subsequent job descriptions, within the same batch
* call.
*
* Use the +{[JOB ID]}+ special syntax to inject URIs from created resources
* into JSON strings in subsequent job descriptions.
*/
@Test
public void refer_to_items_created_earlier_in_the_same_batch_job_streaming() throws Exception {
String jsonString = new PrettyJSON()
.array()
.object()
.key("method") .value("POST")
.key("to") .value("/node")
.key("id") .value(0)
.key("body")
.object()
.key("name").value("bob")
.endObject()
.endObject()
.object()
.key("method") .value("POST")
.key("to") .value("/node")
.key("id") .value(1)
.key("body")
.object()
.key("age").value(12)
.endObject()
.endObject()
.object()
.key("method") .value("POST")
.key("to") .value("{0}/relationships")
.key("id") .value(3)
.key("body")
.object()
.key("to").value("{1}")
.key("data")
.object()
.key("since").value("2010")
.endObject()
.key("type").value("KNOWS")
.endObject()
.endObject()
.object()
.key("method") .value("POST")
.key("to") .value("/index/relationship/my_rels")
.key("id") .value(4)
.key("body")
.object()
.key("key").value("since")
.key("value").value("2010")
.key("uri").value("{3}")
.endObject()
.endObject()
.endArray().toString();
String entity = gen.get()
.expectedType(APPLICATION_JSON_TYPE)
.withHeader(StreamingFormat.STREAM_HEADER, "true")
.expectedStatus(200)
.payload( jsonString )
.post( batchUri() )
.entity();
List<Map<String, Object>> results = JsonHelper.jsonToList(entity);
assertEquals(4, results.size());
// String rels = gen.get()
// .expectedStatus( 200 ).get( getRelationshipIndexUri( "my_rels", "since", "2010")).entity();
// assertEquals(1, JsonHelper.jsonToList( rels ).size());
}
@Test
public void shouldGetLocationHeadersWhenCreatingThings() throws Exception {
int originalNodeCount = countNodes();
final String jsonString = new PrettyJSON()
.array()
.object()
.key("method").value("POST")
.key("to").value("/node")
.key("body")
.object()
.key("age").value(1)
.endObject()
.endObject()
.endArray().toString();
JaxRsResponse response = RestRequest.req()
.accept(APPLICATION_JSON_TYPE)
.header(StreamingFormat.STREAM_HEADER, "true")
.post(batchUri(), jsonString);
assertEquals(200, response.getStatus());
final String entity = response.getEntity();
System.out.println("result = " + entity);
List<Map<String, Object>> results = JsonHelper.jsonToList(entity);
assertEquals(originalNodeCount + 1, countNodes());
assertEquals(1, results.size());
Map<String, Object> result = results.get(0);
assertTrue(((String) result.get("location")).length() > 0);
}
private String batchUri()
{
return getDataUri()+"batch";
}
@Test
public void shouldForwardUnderlyingErrors() throws Exception {
JaxRsResponse response = RestRequest.req().accept(APPLICATION_JSON_TYPE).header(StreamingFormat.STREAM_HEADER,"true")
.post(batchUri(), new PrettyJSON()
.array()
.object()
.key("method").value("POST")
.key("to").value("/node")
.key("body")
.object()
.key("age")
.array()
.value(true)
.value("hello")
.endArray()
.endObject()
.endObject()
.endArray()
.toString());
Map<String, Object> res = singleResult( response, 0 );
assertTrue(((String)res.get("message")).startsWith("Invalid JSON array in POST body"));
assertEquals( 400, res.get( "status" ) );
}
private Map<String, Object> singleResult( JaxRsResponse response, int i ) throws JsonParseException
{
return JsonHelper.jsonToList( response.getEntity() ).get( i );
}
@Test
public void shouldRollbackAllWhenGivenIncorrectRequest() throws JsonParseException, ClientHandlerException,
UniformInterfaceException, JSONException {
String jsonString = new PrettyJSON()
.array()
.object()
.key("method") .value("POST")
.key("to") .value("/node")
.key("body")
.object()
.key("age").value("1")
.endObject()
.endObject()
.object()
.key("method") .value("POST")
.key("to") .value("/node")
.key("body")
.array()
.value("a_list")
.value("this_makes_no_sense")
.endArray()
.endObject()
.endArray()
.toString();
int originalNodeCount = countNodes();
JaxRsResponse response = RestRequest.req()
.accept(APPLICATION_JSON_TYPE)
.header(StreamingFormat.STREAM_HEADER, "true")
.post(batchUri(), jsonString);
assertEquals(200, response.getStatus());
assertTrue(((Map)singleResult( response, 1 ).get("body")).get("message").toString().contains( "java.util.ArrayList cannot be cast to java.util.Map" ));
assertEquals(400, singleResult( response, 1 ).get( "status" ));
assertEquals(originalNodeCount, countNodes());
}
@Test
@SuppressWarnings("unchecked")
public void shouldHandleUnicodeGetCorrectly() throws Exception {
String asianText = "\u4f8b\u5b50";
String germanText = "öäüÖÄÜß";
String complicatedString = asianText + germanText;
String jsonString = new PrettyJSON()
.array()
.object()
.key("method") .value("POST")
.key("to") .value("/node")
.key("body") .object()
.key(complicatedString).value(complicatedString)
.endObject()
.endObject()
.endArray()
.toString();
String entity = gen.get()
.expectedType( APPLICATION_JSON_TYPE )
.withHeader( StreamingFormat.STREAM_HEADER,"true" )
.expectedStatus(200)
.payload( jsonString )
.post( batchUri() )
.entity();
// Pull out the property value from the depths of the response
Map<String, Object> response = (Map<String, Object>) JsonHelper.jsonToList(entity).get(0).get("body");
String returnedValue = (String)((Map<String,Object>)response.get("data")).get(complicatedString);
// Ensure nothing was borked.
assertThat(returnedValue, is(complicatedString));
}
@Test
@Graph("Peter likes Jazz")
public void shouldHandleEscapedStrings() throws ClientHandlerException,
UniformInterfaceException, JSONException, PropertyValueException {
String string = "Jazz";
Node gnode = getNode( string );
assertThat( gnode, inTx(graphdb(), Neo4jMatchers.hasProperty( "name" ).withValue(string)) );
String name = "string\\ and \"test\"";
String jsonString = new PrettyJSON()
.array()
.object()
.key("method") .value("PUT")
.key("to") .value("/node/"+gnode.getId()+"/properties")
.key("body")
.object()
.key("name").value(name)
.endObject()
.endObject()
.endArray()
.toString();
gen.get()
.expectedType(APPLICATION_JSON_TYPE)
.withHeader(StreamingFormat.STREAM_HEADER, "true")
.expectedStatus( 200 )
.payload( jsonString )
.post( batchUri() )
.entity();
jsonString = new PrettyJSON()
.array()
.object()
.key("method") .value("GET")
.key("to") .value("/node/"+gnode.getId()+"/properties/name")
.endObject()
.endArray()
.toString();
String entity = gen.get()
.expectedStatus( 200 )
.payload( jsonString )
.post( batchUri() )
.entity();
List<Map<String, Object>> results = JsonHelper.jsonToList(entity);
assertEquals(results.get(0).get("body"), name);
}
@Test
public void shouldRollbackAllWhenInsertingIllegalData() throws JsonParseException, ClientHandlerException,
UniformInterfaceException, JSONException {
String jsonString = new PrettyJSON()
.array()
.object()
.key("method") .value("POST")
.key("to") .value("/node")
.key("body")
.object()
.key("age").value(1)
.endObject()
.endObject()
.object()
.key("method").value("POST")
.key("to").value("/node")
.key("body")
.object()
.key("age")
.object()
.key("age").value(1)
.endObject()
.endObject()
.endObject()
.endArray().toString();
int originalNodeCount = countNodes();
JaxRsResponse response = RestRequest.req()
.accept(APPLICATION_JSON_TYPE)
.header(StreamingFormat.STREAM_HEADER, "true")
.post(batchUri(), jsonString);
assertEquals(200, response.getStatus());
assertEquals(400, singleResult( response,1 ).get("status"));
assertEquals(originalNodeCount, countNodes());
}
@Test
public void shouldRollbackAllOnSingle404() throws JsonParseException, ClientHandlerException,
UniformInterfaceException, JSONException {
String jsonString = new PrettyJSON()
.array()
.object()
.key("method") .value("POST")
.key("to") .value("/node")
.key("body")
.object()
.key("age").value(1)
.endObject()
.endObject()
.object()
.key("method") .value("POST")
.key("to") .value("www.google.com")
.endObject()
.endArray().toString();
int originalNodeCount = countNodes();
JaxRsResponse response = RestRequest.req()
.accept( APPLICATION_JSON_TYPE )
.header(StreamingFormat.STREAM_HEADER, "true")
.post(batchUri(), jsonString);
assertEquals(200, response.getStatus());
assertEquals(404, singleResult( response ,1 ).get("status"));
assertEquals(originalNodeCount, countNodes());
}
@Test
public void shouldBeAbleToReferToUniquelyCreatedEntities() throws Exception {
String jsonString = new PrettyJSON()
.array()
.object()
.key("method") .value("POST")
.key("to") .value("/index/node/Cultures?unique")
.key("body")
.object()
.key("key").value("ID")
.key("value").value("fra")
.key("properties")
.object()
.key("ID").value("fra")
.endObject()
.endObject()
.key("id") .value(0)
.endObject()
.object()
.key("method") .value("POST")
.key("to") .value("/node")
.key("id") .value(1)
.endObject()
.object()
.key("method") .value("POST")
.key("to") .value("{1}/relationships")
.key("body")
.object()
.key("to").value("{0}")
.key("type").value("has")
.endObject()
.key("id") .value(2)
.endObject()
.endArray().toString();
JaxRsResponse response = RestRequest.req()
.accept( APPLICATION_JSON_TYPE )
.header(StreamingFormat.STREAM_HEADER, "true")
.post(batchUri(), jsonString);
assertEquals(200, response.getStatus());
}
// It has to be possible to create relationships among created and not-created nodes
// in batch operation. Tests the fix for issue #690.
@Test
public void shouldBeAbleToReferToNotCreatedUniqueEntities() throws Exception {
String jsonString = new PrettyJSON()
.array()
.object()
.key("method") .value("POST")
.key("to") .value("/index/node/Cultures?unique")
.key("body")
.object()
.key("key").value("name")
.key("value").value("tobias")
.key("properties")
.object()
.key("name").value("Tobias Tester")
.endObject()
.endObject()
.key("id") .value(0)
.endObject()
.object() // Creates Andres, hence 201 Create
.key("method") .value("POST")
.key("to") .value("/index/node/Cultures?unique")
.key("body")
.object()
.key("key").value("name")
.key("value").value("andres")
.key("properties")
.object()
.key("name").value("Andres Tester")
.endObject()
.endObject()
.key("id") .value(1)
.endObject()
.object() // Duplicated to ID.1, hence 200 OK
.key("method") .value("POST")
.key("to") .value("/index/node/Cultures?unique")
.key("body")
.object()
.key("key").value("name")
.key("value").value("andres")
.key("properties")
.object()
.key("name").value("Andres Tester")
.endObject()
.endObject()
.key("id") .value(2)
.endObject()
.object()
.key("method") .value("POST")
.key("to") .value("/index/relationship/my_rels/?unique")
.key("body")
.object()
.key("key").value("name")
.key("value").value("tobias-andres")
.key("start").value("{0}")
.key("end").value("{1}")
.key("type").value("FRIENDS")
.endObject()
.key("id") .value(3)
.endObject()
.object()
.key("method") .value("POST")
.key("to") .value("/index/relationship/my_rels/?unique")
.key("body")
.object()
.key("key").value("name")
.key("value").value("andres-tobias")
.key("start").value("{2}") // Not-created entity here
.key("end").value("{0}")
.key("type").value("FRIENDS")
.endObject()
.key("id") .value(4)
.endObject()
.object()
.key("method") .value("POST")
.key("to") .value("/index/relationship/my_rels/?unique")
.key("body")
.object()
.key("key").value("name")
.key("value").value("andres-tobias")
.key("start").value("{1}") // Relationship should not be created
.key("end").value("{0}")
.key("type").value("FRIENDS")
.endObject()
.key("id") .value(5)
.endObject()
.endArray().toString();
JaxRsResponse response = RestRequest.req()
.accept( APPLICATION_JSON_TYPE )
.header(StreamingFormat.STREAM_HEADER, "true")
.post(batchUri(), jsonString);
assertEquals(200, response.getStatus());
final String entity = response.getEntity();
System.out.println("entity = " + entity);
List<Map<String, Object>> results = JsonHelper.jsonToList(entity);
assertEquals(6, results.size());
Map<String, Object> andresResult1 = results.get(1);
Map<String, Object> andresResult2 = results.get(2);
Map<String, Object> secondRelationship = results.get(4);
Map<String, Object> thirdRelationship = results.get(5);
// Same people
Map<String, Object> body1 = (Map<String, Object>) andresResult1.get("body");
Map<String, Object> body2 = (Map<String, Object>) andresResult2.get("body");
assertEquals(body1.get("id"), body2.get("id"));
// Same relationship
body1 = (Map<String, Object>) secondRelationship.get("body");
body2 = (Map<String, Object>) thirdRelationship.get("body");
assertEquals(body1.get("self"), body2.get("self"));
// Created for {2} {0}
assertTrue(((String) secondRelationship.get("location")).length() > 0);
// {2} = {1} = Andres
body1 = (Map<String, Object>) secondRelationship.get("body");
body2 = (Map<String, Object>) andresResult1.get("body");
assertEquals(body1.get("start"), body2.get("self"));
}
private int countNodes()
{
try ( Transaction transaction = graphdb().beginTx() )
{
return IteratorUtil.count( (Iterable) GlobalGraphOperations.at(graphdb()).getAllNodes() );
}
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_streaming_StreamingBatchOperationDocIT.java
|
2,615
|
public class UriPathWildcardMatcherTest
{
@Test
public void shouldFailWithoutAsteriskAtStart()
{
UriPathWildcardMatcher matcher = new UriPathWildcardMatcher("/some/uri/path");
assertFalse(matcher.matches("preamble/some/uri/path"));
}
@Test
public void shouldFailWithoutAsteriskAtEnd()
{
UriPathWildcardMatcher matcher = new UriPathWildcardMatcher("/some/uri/path/and/some/more");
assertFalse(matcher.matches("/some/uri/path/with/middle/bit/and/some/more"));
}
@Test
public void shouldMatchAsteriskAtStart()
{
UriPathWildcardMatcher matcher = new UriPathWildcardMatcher("*/some/uri/path");
assertTrue(matcher.matches("anything/i/like/followed/by/some/uri/path"));
assertFalse(matcher.matches("anything/i/like/followed/by/some/deliberately/changed/to/fail/uri/path"));
}
@Test
public void shouldMatchAsteriskAtEnd()
{
UriPathWildcardMatcher matcher = new UriPathWildcardMatcher("/some/uri/path/*");
assertTrue(matcher.matches("/some/uri/path/followed/by/anything/i/like"));
}
@Test
public void shouldMatchAsteriskInMiddle()
{
UriPathWildcardMatcher matcher = new UriPathWildcardMatcher("/some/uri/path/*/and/some/more");
assertTrue(matcher.matches("/some/uri/path/with/middle/bit/and/some/more"));
}
@Test
public void shouldMatchMultipleAsterisksInMiddle()
{
UriPathWildcardMatcher matcher = new UriPathWildcardMatcher("/some/uri/path/*/and/some/more/*/and/a/final/bit");
assertTrue(matcher.matches(
"/some/uri/path/with/middle/bit/and/some/more/with/additional/asterisk/part/and/a/final/bit"));
}
@Test
public void shouldMatchMultipleAsterisksAtStartAndInMiddle()
{
UriPathWildcardMatcher matcher = new UriPathWildcardMatcher(
"*/some/uri/path/*/and/some/more/*/and/a/final/bit");
assertTrue(matcher.matches(
"a/bit/of/preamble/and/then/some/uri/path/with/middle/bit/and/some/more/with/additional/asterisk/part/and/a/final/bit"));
}
@Test
public void shouldMatchMultipleAsterisksAtEndAndInMiddle()
{
UriPathWildcardMatcher matcher = new UriPathWildcardMatcher(
"/some/uri/path/*/and/some/more/*/and/a/final/bit/*");
assertTrue(matcher.matches(
"/some/uri/path/with/middle/bit/and/some/more/with/additional/asterisk/part/and/a/final/bit/and/now/some/post/amble"));
}
@Test
public void shouldMatchMultipleAsterisksAtStartAndEndAndInMiddle()
{
UriPathWildcardMatcher matcher = new UriPathWildcardMatcher(
"*/some/uri/path/*/and/some/more/*/and/a/final/bit/*");
assertTrue(matcher.matches(
"a/bit/of/preamble/and/then//some/uri/path/with/middle/bit/and/some/more/with/additional/asterisk/part/and/a/final/bit/and/now/some/post/amble"));
}
@Test
public void shouldMatchMultipleSimpleString()
{
UriPathWildcardMatcher matcher = new UriPathWildcardMatcher("str");
assertTrue(matcher.matches("str"));
}
@Test
public void shouldMatchMultipleSimpleStringWithALeadingWildcard()
{
UriPathWildcardMatcher matcher = new UriPathWildcardMatcher("*str");
assertTrue(matcher.matches("my_str"));
}
@Test
public void shouldFailToMatchMultipleSimpleStringWithATrailingWildcard()
{
UriPathWildcardMatcher matcher = new UriPathWildcardMatcher("str*");
assertFalse(matcher.matches("my_str"));
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_security_UriPathWildcardMatcherTest.java
|
2,616
|
public class UriPathWildcardMatcher
{
private final String uriPath;
public UriPathWildcardMatcher(String uriPath)
{
this.uriPath = uriPath.replace("*", ".*");
}
public boolean matches(String uri)
{
return uri.matches(uriPath);
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_security_UriPathWildcardMatcher.java
|
2,617
|
public class SecurityRulesDocIT extends ExclusiveServerTestBase
{
private CommunityNeoServer server;
private FunctionalTestHelper functionalTestHelper;
public
@Rule
TestData<RESTDocsGenerator> gen = TestData.producedThrough( RESTDocsGenerator.PRODUCER );
@After
public void stopServer()
{
if ( server != null )
{
server.stop();
}
}
/**
* In this example, a (dummy) failing security rule is registered to deny
* access to all URIs to the server by listing the rules class in
* 'neo4j-server.properties':
*
* @@config
*
* with the rule source code of:
*
* @@failingRule
*
* With this rule registered, any access to the server will be
* denied. In a production-quality implementation the rule
* will likely lookup credentials/claims in a 3rd-party
* directory service (e.g. LDAP) or in a local database of
* authorized users.
*/
@Test
@Documented
@Title("Enforcing Server Authorization Rules")
public void should401WithBasicChallengeWhenASecurityRuleFails()
throws Exception
{
server = CommunityServerBuilder.server().withDefaultDatabaseTuning().withSecurityRules(
PermanentlyFailingSecurityRule.class.getCanonicalName() )
.usingDatabaseDir( folder.getRoot().getAbsolutePath() )
.build();
server.start();
gen.get().addSnippet(
"config",
"\n[source]\n----\norg.neo4j.server.rest.security_rules=my.rules" +
".PermanentlyFailingSecurityRule\n----\n" );
gen.get().addTestSourceSnippets( PermanentlyFailingSecurityRule.class,
"failingRule" );
functionalTestHelper = new FunctionalTestHelper( server );
gen.get().setSection( "ops" );
JaxRsResponse response = gen.get().expectedStatus( 401 ).expectedHeader(
"WWW-Authenticate" ).post( functionalTestHelper.nodeUri() ).response();
assertThat( response.getHeaders().getFirst( "WWW-Authenticate" ),
containsString( "Basic realm=\""
+ PermanentlyFailingSecurityRule.REALM + "\"" ) );
}
@Test
public void should401WithBasicChallengeIfAnyOneOfTheRulesFails()
throws Exception
{
server = CommunityServerBuilder.server().withDefaultDatabaseTuning().withSecurityRules(
PermanentlyFailingSecurityRule.class.getCanonicalName(),
PermanentlyPassingSecurityRule.class.getCanonicalName() )
.usingDatabaseDir( folder.getRoot().getAbsolutePath() )
.build();
server.start();
functionalTestHelper = new FunctionalTestHelper( server );
JaxRsResponse response = gen.get().expectedStatus( 401 ).expectedHeader(
"WWW-Authenticate" ).post( functionalTestHelper.nodeUri() ).response();
assertThat( response.getHeaders().getFirst( "WWW-Authenticate" ),
containsString( "Basic realm=\""
+ PermanentlyFailingSecurityRule.REALM + "\"" ) );
}
@Test
public void shouldInvokeAllSecurityRules() throws Exception
{
// given
server = CommunityServerBuilder.server().withDefaultDatabaseTuning().withSecurityRules(
NoAccessToDatabaseSecurityRule.class.getCanonicalName(),
NoAccessToWebAdminSecurityRule.class.getCanonicalName() )
.usingDatabaseDir( folder.getRoot().getAbsolutePath() )
.build();
server.start();
functionalTestHelper = new FunctionalTestHelper( server );
// when
gen.get().expectedStatus( 401 ).get( functionalTestHelper.dataUri() ).response();
gen.get().expectedStatus( 401 ).expectedType( MediaType.TEXT_HTML_TYPE )
.get( functionalTestHelper.webAdminUri() ).response();
// then
assertTrue( NoAccessToDatabaseSecurityRule.wasInvoked() );
assertTrue( NoAccessToWebAdminSecurityRule.wasInvoked() );
}
@Test
public void shouldRespondWith201IfAllTheRulesPassWhenCreatingANode()
throws Exception
{
server = CommunityServerBuilder.server().withDefaultDatabaseTuning().withSecurityRules(
PermanentlyPassingSecurityRule.class.getCanonicalName() )
.usingDatabaseDir( folder.getRoot().getAbsolutePath() )
.build();
server.start();
functionalTestHelper = new FunctionalTestHelper( server );
gen.get().expectedStatus( 201 ).expectedHeader( "Location" ).post(
functionalTestHelper.nodeUri() ).response();
}
/**
* In this example, a security rule is registered to deny
* access to all URIs to the server by listing the rule(s) class(es) in
* 'neo4j-server.properties'.
* In this case, the rule is registered
* using a wildcard URI path (where `*` characters can be used to signify
* any part of the path). For example `/users*` means the rule
* will be bound to any resources under the `/users` root path. Similarly
* `/users*type*` will bind the rule to resources matching
* URIs like `/users/fred/type/premium`.
*
* @@config
*
* with the rule source code of:
*
* @@failingRuleWithWildcardPath
*
* With this rule registered, any access to URIs under /protected/ will be
* denied by the server. Using wildcards allows flexible targeting of security rules to
* arbitrary parts of the server's API, including any unmanaged extensions or managed
* plugins that have been registered.
*/
@Test
@Documented
@Title("Using Wildcards to Target Security Rules")
public void aSimpleWildcardUriPathShould401OnAccessToProtectedSubPath()
throws Exception
{
String mountPoint = "/protected/tree/starts/here" + DummyThirdPartyWebService.DUMMY_WEB_SERVICE_MOUNT_POINT;
server = CommunityServerBuilder.server().withDefaultDatabaseTuning()
.withThirdPartyJaxRsPackage( "org.dummy.web.service",
mountPoint )
.withSecurityRules(
PermanentlyFailingSecurityRuleWithWildcardPath.class.getCanonicalName() )
.usingDatabaseDir( folder.getRoot().getAbsolutePath() )
.build();
server.start();
gen.get()
.addSnippet(
"config",
"\n[source]\n----\norg.neo4j.server.rest.security_rules=my.rules" +
".PermanentlyFailingSecurityRuleWithWildcardPath\n----\n" );
gen.get().addTestSourceSnippets( PermanentlyFailingSecurityRuleWithWildcardPath.class,
"failingRuleWithWildcardPath" );
gen.get().setSection( "ops" );
functionalTestHelper = new FunctionalTestHelper( server );
JaxRsResponse clientResponse = gen.get()
.expectedStatus( 401 )
.expectedType( MediaType.APPLICATION_JSON_TYPE )
.expectedHeader( "WWW-Authenticate" )
.get( trimTrailingSlash( functionalTestHelper.baseUri() )
+ mountPoint + "/more/stuff" )
.response();
assertEquals( 401, clientResponse.getStatus() );
}
/**
* In this example, a security rule is registered to deny
* access to all URIs matching a complex pattern.
* The config looks like this:
*
* @@config
*
* with the rule source code of:
*
* @@failingRuleWithComplexWildcardPath
*/
@Test
@Documented
@Title("Using Complex Wildcards to Target Security Rules")
public void aComplexWildcardUriPathShould401OnAccessToProtectedSubPath()
throws Exception
{
String mountPoint = "/protected/wildcard_replacement/x/y/z/something/else/more_wildcard_replacement/a/b/c" +
"/final/bit";
server = CommunityServerBuilder.server().withDefaultDatabaseTuning()
.withThirdPartyJaxRsPackage( "org.dummy.web.service",
mountPoint )
.withSecurityRules(
PermanentlyFailingSecurityRuleWithComplexWildcardPath.class.getCanonicalName() )
.usingDatabaseDir( folder.getRoot().getAbsolutePath() )
.build();
server.start();
gen.get().addSnippet(
"config",
"\n[source]\n----\norg.neo4j.server.rest.security_rules=my.rules" +
".PermanentlyFailingSecurityRuleWithComplexWildcardPath\n----\n" );
gen.get().addTestSourceSnippets( PermanentlyFailingSecurityRuleWithComplexWildcardPath.class,
"failingRuleWithComplexWildcardPath" );
gen.get().setSection( "ops" );
functionalTestHelper = new FunctionalTestHelper( server );
JaxRsResponse clientResponse = gen.get()
.expectedStatus( 401 )
.expectedType( MediaType.APPLICATION_JSON_TYPE )
.expectedHeader( "WWW-Authenticate" )
.get( trimTrailingSlash( functionalTestHelper.baseUri() )
+ mountPoint + "/more/stuff" )
.response();
assertEquals( 401, clientResponse.getStatus() );
}
private String trimTrailingSlash( URI uri )
{
String result = uri.toString();
if ( result.endsWith( "/" ) )
{
return result.substring( 0, result.length() - 1 );
}
else
{
return result;
}
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_security_SecurityRulesDocIT.java
|
2,618
|
public class SecurityFilterTest
{
@Test
public void shouldPassThroughRequestToAnUnsecuredPath() throws Exception
{
// given
SecurityRule rule = mock( SecurityRule.class );
when( rule.forUriPath() ).thenReturn( "/some-path" );
FilterChain filterChain = mock( FilterChain.class );
SecurityFilter securityFilter = new SecurityFilter( rule );
HttpServletRequest request = mock( HttpServletRequest.class );
when( request.getContextPath() ).thenReturn( "/some-other-path" );
// when
securityFilter.doFilter( request, mock( HttpServletResponse.class ), filterChain );
// then
verify( filterChain ).doFilter( any( HttpServletRequest.class ), any( HttpServletResponse.class ) );
}
@Test
public void shouldActivateRuleThatRejectsTheRequestForAMatchingPath() throws Exception
{
// given
SecurityRule rule = mock( SecurityRule.class );
when( rule.forUriPath() ).thenReturn( "/some-path" );
when( rule.isAuthorized( any( HttpServletRequest.class ) ) ).thenReturn( false );
FilterChain filterChain = mock( FilterChain.class );
SecurityFilter securityFilter = new SecurityFilter( rule );
HttpServletRequest request = mock( HttpServletRequest.class );
when( request.getContextPath() ).thenReturn( "/some-path" );
// when
securityFilter.doFilter( request, mock( HttpServletResponse.class ), filterChain );
// then
verify( filterChain, times(0) ).doFilter( any( HttpServletRequest.class ), any( HttpServletResponse.class ) );
}
@Test
public void shouldActivateRuleThatAcceptsTheRequestForAMatchingPath() throws Exception
{
// given
SecurityRule rule = mock( SecurityRule.class );
when( rule.forUriPath() ).thenReturn( "/some-path" );
when( rule.isAuthorized( any( HttpServletRequest.class ) ) ).thenReturn( true );
FilterChain filterChain = mock( FilterChain.class );
SecurityFilter securityFilter = new SecurityFilter( rule );
HttpServletRequest request = mock( HttpServletRequest.class );
when( request.getContextPath() ).thenReturn( "/some-path" );
HttpServletResponse response = mock( HttpServletResponse.class );
// when
securityFilter.doFilter( request, response, filterChain );
// then
verify( filterChain ).doFilter( request, response );
}
@Test
public void shouldRemoveRules() throws Exception
{
// given
SecurityRule securityRule1 = mock( SecurityRule.class );
when( securityRule1.forUriPath() ).thenReturn( "/securityRule1" );
SecurityRule securityRule2 = mock( SecurityRule.class );
when( securityRule2.forUriPath() ).thenReturn( "/securityRule2" );
SecurityFilter securityFilter = new SecurityFilter( securityRule1, securityRule2 );
HttpServletRequest request = mock( HttpServletRequest.class );
HttpServletResponse response = mock( HttpServletResponse.class );
FilterChain filterChain = mock( FilterChain.class );
// when
securityFilter.destroy();
securityFilter.doFilter( request, response, filterChain );
// then
verify( filterChain ).doFilter( request, response );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_security_SecurityFilterTest.java
|
2,619
|
public class SecurityFilter implements Filter
{
private final HashMap<UriPathWildcardMatcher, HashSet<SecurityRule>> rules = new HashMap<UriPathWildcardMatcher, HashSet<SecurityRule>>();
public SecurityFilter( SecurityRule rule, SecurityRule... rules )
{
this( merge( rule, rules ) );
}
public SecurityFilter( Iterable<SecurityRule> securityRules )
{
// For backwards compatibility
for ( SecurityRule r : securityRules )
{
String rulePath = r.forUriPath();
if ( !rulePath.endsWith( "*" ) )
{
rulePath = rulePath + "*";
}
UriPathWildcardMatcher uriPathWildcardMatcher = new UriPathWildcardMatcher( rulePath );
HashSet<SecurityRule> ruleHashSet = rules.get( uriPathWildcardMatcher );
if ( ruleHashSet == null )
{
ruleHashSet = new HashSet<SecurityRule>();
rules.put( uriPathWildcardMatcher, ruleHashSet );
}
ruleHashSet.add( r );
}
}
private static Iterable<SecurityRule> merge( SecurityRule rule, SecurityRule[] rules )
{
ArrayList<SecurityRule> result = new ArrayList<SecurityRule>();
result.add( rule );
Collections.addAll( result, rules );
return result;
}
@Override
public void init( FilterConfig filterConfig ) throws ServletException
{
}
@Override
public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException,
ServletException
{
validateRequestType( request );
validateResponseType( response );
HttpServletRequest httpReq = (HttpServletRequest) request;
String path = httpReq.getContextPath() + (httpReq.getPathInfo() == null ? "" : httpReq.getPathInfo());
for ( UriPathWildcardMatcher uriPathWildcardMatcher : rules.keySet() )
{
if ( uriPathWildcardMatcher.matches( path ) )
{
HashSet<SecurityRule> securityRules = rules.get( uriPathWildcardMatcher );
for ( SecurityRule securityRule : securityRules )
{
// 401 on the first failed rule we come along
if ( !securityRule.isAuthorized( httpReq ) )
{
createUnauthorizedChallenge( response, securityRule );
return;
}
}
}
}
chain.doFilter( request, response );
}
private void validateRequestType( ServletRequest request ) throws ServletException
{
if ( !(request instanceof HttpServletRequest) )
{
throw new ServletException( String.format( "Expected HttpServletRequest, received [%s]", request.getClass()
.getCanonicalName() ) );
}
}
private void validateResponseType( ServletResponse response ) throws ServletException
{
if ( !(response instanceof HttpServletResponse) )
{
throw new ServletException( String.format( "Expected HttpServletResponse, received [%s]",
response.getClass()
.getCanonicalName() ) );
}
}
private void createUnauthorizedChallenge( ServletResponse response, SecurityRule rule )
{
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
httpServletResponse.setStatus( 401 );
httpServletResponse.addHeader( "WWW-Authenticate", rule.wwwAuthenticateHeader() );
}
@Override
public synchronized void destroy()
{
rules.clear();
}
public static String basicAuthenticationResponse( String realm )
{
return "Basic realm=\"" + realm + "\"";
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_security_SecurityFilter.java
|
2,620
|
public class PermanentlyPassingSecurityRule implements SecurityRule {
public static final String REALM = "WallyWorld"; // as per RFC2617 :-);
@Override
public boolean isAuthorized( HttpServletRequest request )
{
return true; // always passes
}
@Override
public String forUriPath()
{
return SecurityRule.DEFAULT_DATABASE_PATH;
}
@Override
public String wwwAuthenticateHeader()
{
return REALM;
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_security_PermanentlyPassingSecurityRule.java
|
2,621
|
public class PermanentlyFailingSecurityRuleWithWildcardPath implements SecurityRule
{
public static final String REALM = "WallyWorld"; // as per RFC2617 :-)
public boolean isAuthorized( HttpServletRequest request )
{
return false;
}
//START SNIPPET: failingRuleWithWildcardPath
public String forUriPath()
{
return "/protected/*";
}
// END SNIPPET: failingRuleWithWildcardPath
public String wwwAuthenticateHeader()
{
return SecurityFilter.basicAuthenticationResponse(REALM);
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_security_PermanentlyFailingSecurityRuleWithWildcardPath.java
|
2,622
|
public class PermanentlyFailingSecurityRuleWithComplexWildcardPath implements SecurityRule
{
public static final String REALM = "WallyWorld"; // as per RFC2617 :-)
@Override
public boolean isAuthorized( HttpServletRequest request )
{
return false;
}
@Override
public String forUriPath()
{
return "/protected/*/something/else/*/final/bit";
}
@Override
public String wwwAuthenticateHeader()
{
return SecurityFilter.basicAuthenticationResponse(REALM);
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_security_PermanentlyFailingSecurityRuleWithComplexWildcardPath.java
|
2,623
|
public class PermanentlyFailingSecurityRule implements SecurityRule
{
public static final String REALM = "WallyWorld"; // as per RFC2617 :-)
@Override
public boolean isAuthorized( HttpServletRequest request )
{
return false; // always fails - a production implementation performs
// deployment-specific authorization logic here
}
@Override
public String forUriPath()
{
return "/*";
}
@Override
public String wwwAuthenticateHeader()
{
return SecurityFilter.basicAuthenticationResponse(REALM);
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_security_PermanentlyFailingSecurityRule.java
|
2,624
|
public class NoAccessToWebAdminSecurityRule implements SecurityRule
{
private static boolean wasInvoked = false;
public static boolean wasInvoked()
{
return wasInvoked;
}
@Override
public boolean isAuthorized( HttpServletRequest request )
{
wasInvoked = true;
return false;
}
@Override
public String forUriPath()
{
return "/webadmin*";
}
@Override
public String wwwAuthenticateHeader()
{
return SecurityFilter.basicAuthenticationResponse("WallyWorld");
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_security_NoAccessToWebAdminSecurityRule.java
|
2,625
|
{
@Override
public Boolean answer( InvocationOnMock invocation ) throws Throwable
{
latch.startAndAwaitFinish();
return false;
}
} );
| false
|
community_server_src_test_java_org_neo4j_server_rest_transactional_ConcurrentTransactionAccessTest.java
|
2,626
|
private static class DisgustingUriScheme implements TransactionUriScheme
{
private static long parseTxId( URI txUri )
{
return parseLong( txUri.toString() );
}
@Override
public URI txUri( long id )
{
return URI.create( String.valueOf( id ) );
}
@Override
public URI txCommitUri( long id )
{
return txUri( id );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_transactional_ConcurrentTransactionAccessTest.java
|
2,627
|
@Provider
public class AuthenticationExceptionMapper implements ExceptionMapper<AuthenticationException>
{
public Response toResponse( AuthenticationException e )
{
if ( e.getRealm() != null )
{
return Response.status( Status.UNAUTHORIZED )
.header( "WWW-Authenticate", "Basic realm=\"" + e.getRealm() + "\"" )
.type( "text/plain" )
.entity( e.getMessage() )
.build();
}
else
{
return Response.status( Status.UNAUTHORIZED )
.type( "text/plain" )
.entity( e.getMessage() )
.build();
}
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_security_AuthenticationExceptionMapper.java
|
2,628
|
public class DeserializationException extends Exception
{
DeserializationException( String message )
{
super( message );
}
DeserializationException( String message, Throwable cause )
{
super( message + ": " + cause.getMessage(), cause );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_transactional_DeserializationException.java
|
2,629
|
public class TransactionDocTest extends AbstractRestFunctionalTestBase
{
/**
* Begin a transaction
*
* You begin a new transaction by posting zero or more Cypher statements
* to the transaction endpoint. The server will respond with the result of
* your statements, as well as the location of your open transaction.
*/
@Test
@Documented
public void begin_a_transaction() throws PropertyValueException
{
// Document
ResponseEntity response = gen.get()
.noGraph()
.expectedStatus( 201 )
.payload( quotedJson( "{ 'statements': [ { 'statement': 'CREATE (n {props}) RETURN n', " +
"'parameters': { 'props': { 'name': 'My Node' } } } ] }" ) )
.post( getDataUri() + "transaction" );
// Then
Map<String, Object> result = jsonToMap( response.entity() );
assertNoErrors( result );
Map<String, Object> node = resultCell( result, 0, 0 );
assertThat( (String) node.get( "name" ), equalTo( "My Node" ) );
}
/**
* Execute statements in an open transaction
*
* Given that you have an open transaction, you can make a number of requests, each of which executes additional
* statements, and keeps the transaction open by resetting the transaction timeout.
*/
@Test
@Documented
public void execute_statements_in_an_open_transaction() throws PropertyValueException
{
// Given
String location = POST( getDataUri() + "transaction" ).location();
// Document
ResponseEntity response = gen.get()
.noGraph()
.expectedStatus( 200 )
.payload( quotedJson( "{ 'statements': [ { 'statement': 'CREATE n RETURN n' } ] }" ) )
.post( location );
// Then
Map<String, Object> result = jsonToMap( response.entity() );
assertNoErrors( result );
}
/**
* Execute statements in an open transaction in REST format for the return.
*
* Given that you have an open transaction, you can make a number of requests, each of which executes additional
* statements, and keeps the transaction open by resetting the transaction timeout. Specifying the `REST` format will
* give back full Neo4j Rest API representations of the Neo4j Nodes, Relationships and Paths, if returned.
*/
@Test
@Documented
public void execute_statements_in_an_open_transaction_using_REST() throws PropertyValueException
{
// Given
String location = POST( getDataUri() + "transaction" ).location();
// Document
ResponseEntity response = gen.get()
.noGraph()
.expectedStatus( 200 )
.payload( quotedJson( "{ 'statements': [ { 'statement': 'CREATE n RETURN n','resultDataContents':['REST'] } ] }" ) )
.post( location );
// Then
Map<String, Object> result = jsonToMap( response.entity() );
ArrayList rest = (ArrayList) ((Map)((ArrayList)((Map)((ArrayList)result.get("results")).get(0)) .get("data")).get(0)).get("rest");
String selfUri = ((String)((Map)rest.get(0)).get("self"));
assertTrue(selfUri.startsWith(getDatabaseUri()));
assertNoErrors( result );
}
/**
* Reset transaction timeout of an open transaction
*
* Every orphaned transaction is automatically expired after a period of inactivity. This may be prevented
* by resetting the transaction timeout.
*
* The timeout may be reset by sending a keep-alive request to the server that executes an empty list of statements.
* This request will reset the transaction timeout and return the new time at which the transaction will
* expire as an RFC1123 formatted timestamp value in the ``transaction'' section of the response.
*/
@Test
@Documented
public void reset_transaction_timeout_of_an_open_transaction()
throws PropertyValueException, ParseException, InterruptedException
{
// Given
HTTP.Response initialResponse = POST( getDataUri() + "transaction" );
String location = initialResponse.location();
long initialExpirationTime = expirationTime( jsonToMap( initialResponse.rawContent() ) );
// This generous wait time is necessary to compensate for limited resolution of RFC 1123 timestamps
// and the fact that the system clock is allowed to run "backwards" between threads
// (cf. http://stackoverflow.com/questions/2978598)
//
Thread.sleep( 3000 );
// Document
ResponseEntity response = gen.get()
.noGraph()
.expectedStatus( 200 )
.payload( quotedJson( "{ 'statements': [ ] }" ) )
.post( location );
// Then
Map<String, Object> result = jsonToMap( response.entity() );
assertNoErrors( result );
long newExpirationTime = expirationTime( result );
assertTrue( "Expiration time was not increased", newExpirationTime > initialExpirationTime );
}
/**
* Commit an open transaction
*
* Given you have an open transaction, you can send a commit request. Optionally, you submit additional statements
* along with the request that will be executed before committing the transaction.
*/
@Test
@Documented
public void commit_an_open_transaction() throws PropertyValueException
{
// Given
String location = POST( getDataUri() + "transaction" ).location();
// Document
ResponseEntity response = gen.get()
.noGraph()
.expectedStatus( 200 )
.payload( quotedJson( "{ 'statements': [ { 'statement': 'CREATE n RETURN id(n)' } ] }" ) )
.post( location + "/commit" );
// Then
Map<String, Object> result = jsonToMap( response.entity() );
assertNoErrors( result );
Integer id = resultCell( result, 0, 0 );
assertThat( GET( getNodeUri( id ) ).status(), is( 200 ) );
}
/**
* Begin and commit a transaction in one request
*
* If there is no need to keep a transaction open across multiple HTTP requests, you can begin a transaction,
* execute statements, and commit with just a single HTTP request.
*/
@Test
@Documented
public void begin_and_commit_a_transaction_in_one_request() throws PropertyValueException
{
// Document
ResponseEntity response = gen.get()
.noGraph()
.expectedStatus( 200 )
.payload( quotedJson( "{ 'statements': [ { 'statement': 'CREATE n RETURN id(n)' } ] }" ) )
.post( getDataUri() + "transaction/commit" );
// Then
Map<String, Object> result = jsonToMap( response.entity() );
assertNoErrors( result );
Integer id = resultCell( result, 0, 0 );
assertThat( GET( getNodeUri( id ) ).status(), is( 200 ) );
}
/**
* Return results in graph format
*
* If you want to understand the graph structure of nodes and relationships returned by your query,
* you can specify the "graph" results data format. For example, this is useful when you want to visualise the
* graph structure. The format collates all the nodes and relationships from all columns of the result,
* and also flattens collections of nodes and relationships, including paths.
*/
@Test
@Documented
public void return_results_in_graph_format() throws PropertyValueException
{
// Document
ResponseEntity response = gen.get()
.noGraph()
.expectedStatus( 200 )
.payload( quotedJson( "{'statements':[{'statement':" +
"'CREATE ( bike:Bike { weight: 10 } )" +
"CREATE ( frontWheel:Wheel { spokes: 3 } )" +
"CREATE ( backWheel:Wheel { spokes: 32 } )" +
"CREATE p1 = bike -[:HAS { position: 1 } ]-> frontWheel " +
"CREATE p2 = bike -[:HAS { position: 2 } ]-> backWheel " +
"RETURN bike, p1, p2', " +
"'resultDataContents': ['row','graph']}] }" ) )
.post( getDataUri() + "transaction/commit" );
// Then
Map<String, Object> result = jsonToMap( response.entity() );
assertNoErrors( result );
Map<String, List<Object>> row = graphRow( result, 0 );
assertEquals( 3, row.get( "nodes" ).size() );
assertEquals( 2, row.get( "relationships" ).size() );
}
/**
* Rollback an open transaction
*
* Given that you have an open transaction, you can send a roll back request. The server will roll back the
* transaction.
*/
@Test
@Documented
public void rollback_an_open_transaction() throws PropertyValueException
{
// Given
HTTP.Response firstReq = POST( getDataUri() + "transaction",
HTTP.RawPayload.quotedJson( "{ 'statements': [ { 'statement': 'CREATE n RETURN id(n)' } ] }" ) );
String location = firstReq.location();
// Document
ResponseEntity response = gen.get()
.noGraph()
.expectedStatus( 200 )
.delete( location + "" );
// Then
Map<String, Object> result = jsonToMap( response.entity() );
assertNoErrors( result );
Integer id = resultCell( firstReq, 0, 0 );
assertThat( GET( getNodeUri( id ) ).status(), is( 404 ) );
}
/**
* Handling errors
*
* The result of any request against the transaction endpoint is streamed back to the client.
* Therefore the server does not know whether the request will be successful or not when it sends the HTTP status
* code.
*
* Because of this, all requests against the transactional endpoint will return 200 or 201 status code, regardless
* of whether statements were successfully executed. At the end of the response payload, the server includes a list
* of errors that occurred while executing statements. If this list is empty, the request completed successfully.
*
* If any errors occur while executing statements, the server will roll back the transaction.
*
* In this example, we send the server an invalid statement to demonstrate error handling.
*
* For more information on the status codes, see <<status-codes>>.
*/
@Test
@Documented
public void handling_errors() throws PropertyValueException
{
// Given
String location = POST( getDataUri() + "transaction" ).location();
// Document
ResponseEntity response = gen.get()
.noGraph()
.expectedStatus( 200 )
.payload( quotedJson( "{ 'statements': [ { 'statement': 'This is not a valid Cypher Statement.' } ] }" ) )
.post( location + "/commit" );
// Then
Map<String, Object> result = jsonToMap( response.entity() );
assertErrors( result, Status.Statement.InvalidSyntax );
}
private void assertNoErrors( Map<String, Object> response )
{
assertErrors( response );
}
private void assertErrors( Map<String, Object> response, Status... expectedErrors )
{
@SuppressWarnings("unchecked")
Iterator<Map<String, Object>> errors = ((List<Map<String, Object>>) response.get( "errors" )).iterator();
Iterator<Status> expected = iterator( expectedErrors );
while ( expected.hasNext() )
{
assertTrue( errors.hasNext() );
assertThat( (String)errors.next().get( "code" ), equalTo( expected.next().code().serialize() ) );
}
if ( errors.hasNext() )
{
Map<String, Object> error = errors.next();
fail( "Expected no more errors, but got " + error.get( "code" ) + " - '" + error.get( "message" ) + "'." );
}
}
private <T> T resultCell( HTTP.Response response, int row, int column )
{
return resultCell( response.<Map<String, Object>>content(), row, column );
}
@SuppressWarnings("unchecked")
private <T> T resultCell( Map<String, Object> response, int row, int column )
{
Map<String, Object> result = ((List<Map<String, Object>>) response.get( "results" )).get( 0 );
List<Map<String,List>> data = (List<Map<String,List>>) result.get( "data" );
return (T) data.get( row ).get( "row" ).get( column );
}
@SuppressWarnings("unchecked")
private Map<String, List<Object>> graphRow( Map<String, Object> response, int row )
{
Map<String, Object> result = ((List<Map<String, Object>>) response.get( "results" )).get( 0 );
List<Map<String,List>> data = (List<Map<String,List>>) result.get( "data" );
return (Map<String,List<Object>>) data.get( row ).get( "graph" );
}
private String quotedJson( String singleQuoted )
{
return singleQuoted.replaceAll( "'", "\"" );
}
private long expirationTime( Map<String, Object> entity ) throws ParseException
{
String timestampString = (String) ( (Map<?, ?>) entity.get( "transaction" ) ).get( "expires" );
return RFC1123.parseTimestamp( timestampString ).getTime();
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_transactional_TransactionDocTest.java
|
2,630
|
public class StubStatementDeserializer extends StatementDeserializer
{
private final Iterator<Statement> statements;
private final Iterator<Neo4jError> errors;
public static StubStatementDeserializer statements( Statement... statements )
{
return new StubStatementDeserializer( IteratorUtil.<Neo4jError>emptyIterator(), iterator( statements ) );
}
public static StubStatementDeserializer deserilizationErrors( Neo4jError... errors )
{
return new StubStatementDeserializer( iterator( errors ), IteratorUtil.<Statement>emptyIterator() );
}
public StubStatementDeserializer( Iterator<Neo4jError> errors, Iterator<Statement> statements )
{
super( new ByteArrayInputStream( new byte[]{} ) );
this.statements = statements;
this.errors = errors;
}
@Override
public boolean hasNext()
{
return statements.hasNext();
}
@Override
public Statement next()
{
return statements.next();
}
@Override
public Iterator<Neo4jError> errors()
{
return errors;
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_transactional_StubStatementDeserializer.java
|
2,631
|
{
@Override
public String toString()
{
return "TestInputStream";
}
} );
| false
|
community_server_src_test_java_org_neo4j_server_rest_transactional_StatementDeserializerTest.java
|
2,632
|
public class StatementDeserializerTest
{
@Test
@SuppressWarnings("unchecked")
public void shouldDeserializeSingleStatement() throws Exception
{
// Given
String json = createJsonFrom( map( "statements", asList( map( "statement", "Blah blah", "parameters", map( "one", 12 ) ) ) ) );
// When
StatementDeserializer de = new StatementDeserializer( new ByteArrayInputStream( json.getBytes( "UTF-8" ) ) );
// Then
assertThat( de.hasNext(), equalTo( true ) );
Statement stmt = de.next();
assertThat( stmt.statement(), equalTo( "Blah blah" ) );
assertThat( stmt.parameters(), equalTo( map( "one", 12 ) ) );
assertThat( de.hasNext(), equalTo( false ) );
}
@Test
public void shouldRejectMapWithADifferentFieldBeforeStatement() throws Exception
{
// NOTE: We don't really want this behaviour, but it's a symptom of keeping
// streaming behaviour while moving the statement list into a map.
String json = "{ \"timeout\" : 200, \"statements\" : [ { \"statement\" : \"ignored\", \"parameters\" : {}} ] }";
assertYieldsErrors( json,
new Neo4jError( Status.Request.InvalidFormat,
new DeserializationException( "Unable to deserialize request. Expected first field to be 'statements', but was 'timeout'." )));
}
@Test
public void shouldTotallyIgnoreInvalidJsonAfterStatementArrayHasFinished() throws Exception
{
// NOTE: We don't really want this behaviour, but it's a symptom of keeping
// streaming behaviour while moving the statement list into a map.
// Given
String json = "{ \"statements\" : [ { \"statement\" : \"Blah blah\", \"parameters\" : {\"one\" : 12}} ] " +
"totally invalid json is totally ignored";
// When
StatementDeserializer de = new StatementDeserializer( new ByteArrayInputStream( json.getBytes( "UTF-8" ) ) );
// Then
assertThat( de.hasNext(), equalTo( true ) );
Statement stmt = de.next();
assertThat( stmt.statement(), equalTo( "Blah blah" ) );
assertThat( de.hasNext(), equalTo( false ) );
}
@Test
public void shouldIgnoreUnknownFields() throws Exception
{
// Given
String json = "{ \"statements\" : [ { \"a\" : \"\", \"b\" : { \"k\":1 }, \"statement\" : \"blah\" } ] }";
// When
StatementDeserializer de = new StatementDeserializer( new ByteArrayInputStream( json.getBytes( "UTF-8" ) ) );
// Then
assertThat( de.hasNext(), equalTo( true ) );
assertThat( de.next().statement(), equalTo( "blah" ) );
assertThat( de.hasNext(), equalTo( false ) );
}
@Test
public void shouldTakeParametersBeforeStatement() throws Exception
{
// Given
String json = "{ \"statements\" : [ { \"a\" : \"\", \"parameters\" : { \"k\":1 }, \"statement\" : \"blah\"}]}";
// When
StatementDeserializer de = new StatementDeserializer( new ByteArrayInputStream( json.getBytes( "UTF-8" ) ) );
// Then
assertThat( de.hasNext(), equalTo( true ) );
Statement stmt = de.next();
assertThat( stmt.statement(), equalTo( "blah" ) );
assertThat( stmt.parameters(), equalTo( map("k", 1) ) );
assertThat( de.hasNext(), equalTo( false ) );
}
@Test
public void shouldTreatEmptyInputStreamAsEmptyStatementList() throws Exception
{
// Given
byte[] json = new byte[0];
// When
StatementDeserializer de = new StatementDeserializer( new ByteArrayInputStream( json ) );
// Then
assertFalse( de.hasNext() );
assertFalse( de.errors().hasNext() );
}
@Test
@SuppressWarnings("unchecked")
public void shouldDeserializeMultipleStatements() throws Exception
{
// Given
String json = createJsonFrom( map( "statements", asList(
map( "statement", "Blah blah", "parameters", map( "one", 12 ) ),
map( "statement", "Blah bluh", "parameters", map( "asd", asList( "one, two" ) ) ) ) ) );
// When
StatementDeserializer de = new StatementDeserializer( new ByteArrayInputStream( json.getBytes( "UTF-8" ) ) );
// Then
assertThat( de.hasNext(), equalTo( true ) );
Statement stmt = de.next();
assertThat( stmt.statement(), equalTo( "Blah blah" ) );
assertThat( stmt.parameters(), equalTo( map( "one", 12 ) ) );
assertThat( de.hasNext(), equalTo( true ) );
Statement stmt2 = de.next();
assertThat( stmt2.statement(), equalTo( "Blah bluh" ) );
assertThat( stmt2.parameters(), equalTo( map( "asd", asList( "one, two" ) ) ) );
assertThat( de.hasNext(), equalTo( false ) );
}
@Test
public void shouldNotThrowButReportErrorOnInvalidInput() throws Exception
{
assertYieldsErrors( "{}",
new Neo4jError( Status.Request.InvalidFormat, new DeserializationException( "Unable to " +
"deserialize request. " +
"Expected [START_OBJECT, FIELD_NAME, START_ARRAY], " +
"found [START_OBJECT, END_OBJECT, null]." ) ) );
assertYieldsErrors( "{ \"statements\":\"WAIT WAT A STRING NOO11!\" }",
new Neo4jError( Status.Request.InvalidFormat, new DeserializationException( "Unable to " +
"deserialize request. Expected [START_OBJECT, FIELD_NAME, START_ARRAY], found [START_OBJECT, " +
"FIELD_NAME, VALUE_STRING]." ) ) );
assertYieldsErrors( "[{]}",
new Neo4jError( Status.Request.InvalidFormat,
new DeserializationException( "Unable to deserialize request: Unexpected close marker ']': " +
"expected '}' " +
"(for OBJECT starting at [Source: TestInputStream; line: 1, column: 1])\n " +
"at [Source: TestInputStream; line: 1, column: 4]" ) ) );
assertYieldsErrors( "{ \"statements\" : \"ITS A STRING\" }",
new Neo4jError( Status.Request.InvalidFormat,
new DeserializationException( "Unable to deserialize request. " +
"Expected [START_OBJECT, FIELD_NAME, START_ARRAY], " +
"found [START_OBJECT, FIELD_NAME, VALUE_STRING]." ) ) );
assertYieldsErrors( "{ \"statements\" : [ { \"statement\" : [\"dd\"] } ] }",
new Neo4jError( Status.Request.InvalidFormat,
new DeserializationException( "Unable to deserialize request: Can not deserialize instance of" +
" java.lang.String out of START_ARRAY token\n at [Source: TestInputStream; line: 1, " +
"column: 22]" ) ) );
assertYieldsErrors( "{ \"statements\" : [ { \"statement\" : \"stmt\", \"parameters\" : [\"AN ARRAY!!\"] } ] }",
new Neo4jError( Status.Request.InvalidFormat,
new DeserializationException( "Unable to deserialize request: Can not deserialize instance of" +
" java.util.LinkedHashMap out of START_ARRAY token\n at [Source: TestInputStream; " +
"line: 1, column: 42]" ) ) );
}
private void assertYieldsErrors( String json, Neo4jError... expectedErrors ) throws UnsupportedEncodingException
{
StatementDeserializer de = new StatementDeserializer( new ByteArrayInputStream( json.getBytes( "UTF-8" ) )
{
@Override
public String toString()
{
return "TestInputStream";
}
} );
while ( de.hasNext() )
{
de.next();
}
Iterator<Neo4jError> actual = de.errors();
Iterator<Neo4jError> expected = asList( expectedErrors ).iterator();
while ( actual.hasNext() )
{
assertTrue( expected.hasNext() );
Neo4jError error = actual.next();
Neo4jError expectedError = expected.next();
assertThat( error.getMessage(), equalTo( expectedError.getMessage() ) );
assertThat( error.status(), equalTo( expectedError.status() ) );
}
assertFalse( expected.hasNext() );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_transactional_StatementDeserializerTest.java
|
2,633
|
public class StatementDeserializer extends PrefetchingIterator<Statement>
{
private static final JsonFactory JSON_FACTORY = new JsonFactory().setCodec( new Neo4jJsonCodec() );
private static final Map<String, Object> NO_PARAMETERS = unmodifiableMap( map() );
private static final Iterator<Neo4jError> NO_ERRORS = emptyIterator();
private final JsonParser input;
private State state;
private List<Neo4jError> errors = null;
private enum State
{
BEFORE_OUTER_ARRAY,
IN_BODY,
FINISHED
}
public StatementDeserializer( InputStream input )
{
try
{
this.input = JSON_FACTORY.createJsonParser( input );
this.state = State.BEFORE_OUTER_ARRAY;
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
}
public Iterator<Neo4jError> errors()
{
return errors == null ? NO_ERRORS : errors.iterator();
}
@Override
protected Statement fetchNextOrNull()
{
try
{
if ( errors != null )
{
return null;
}
switch ( state )
{
case BEFORE_OUTER_ARRAY:
if ( !beginsWithCorrectTokens() )
{
return null;
}
state = State.IN_BODY;
case IN_BODY:
String statement = null;
Map<String, Object> parameters = null;
List<Object> resultsDataContents = null;
boolean includeStats = false;
JsonToken tok;
while ( (tok = input.nextToken()) != null && tok != END_OBJECT )
{
if ( tok == END_ARRAY )
{
// No more statements
state = State.FINISHED;
return null;
}
input.nextValue();
String currentName = input.getCurrentName();
switch ( currentName )
{
case "statement":
statement = input.readValueAs( String.class );
break;
case "parameters":
parameters = readMap( input );
break;
case "resultDataContents":
resultsDataContents = readArray( input );
break;
case "includeStats":
includeStats = input.getBooleanValue();
break;
default:
discardValue( input );
}
}
if ( statement == null )
{
addError( new Neo4jError( Status.Request.InvalidFormat, new DeserializationException( "No statement provided." ) ) );
return null;
}
return new Statement( statement, parameters == null ? NO_PARAMETERS : parameters, includeStats,
ResultDataContent.fromNames( resultsDataContents ) );
case FINISHED:
return null;
}
return null;
}
catch ( JsonParseException | JsonMappingException e )
{
addError( new Neo4jError( Status.Request.InvalidFormat,
new DeserializationException( "Unable to deserialize request", e ) ) );
return null;
}
catch ( IOException e )
{
addError( new Neo4jError( Status.Network.UnknownFailure, e ) );
return null;
}
catch ( Exception e)
{
addError( new Neo4jError( Status.General.UnknownFailure, e ) );
return null;
}
}
private void discardValue( JsonParser input ) throws IOException
{
// This could be done without building up an object
input.readValueAs( Object.class );
}
@SuppressWarnings("unchecked")
private static Map<String, Object> readMap( JsonParser input ) throws IOException
{
return input.readValueAs( Map.class );
}
@SuppressWarnings("unchecked")
private static List<Object> readArray( JsonParser input ) throws IOException
{
return input.readValueAs( List.class );
}
private void addError( Neo4jError error )
{
if ( errors == null )
{
errors = new LinkedList<>();
}
errors.add( error );
}
private boolean beginsWithCorrectTokens() throws IOException
{
List<JsonToken> expectedTokens = asList( START_OBJECT, FIELD_NAME, START_ARRAY );
String expectedField = "statements";
List<JsonToken> foundTokens = new ArrayList<>();
for ( int i = 0; i < expectedTokens.size(); i++ )
{
JsonToken token = input.nextToken();
if ( i == 0 && token == null )
{
return false;
}
if ( token == FIELD_NAME && !expectedField.equals( input.getText() ) )
{
addError( new Neo4jError(
Status.Request.InvalidFormat,
new DeserializationException( String.format( "Unable to deserialize request. " +
"Expected first field to be '%s', but was '%s'.",
expectedField, input.getText() ) ) ) );
return false;
}
foundTokens.add( token );
}
if ( !expectedTokens.equals( foundTokens ) )
{
addError( new Neo4jError(
Status.Request.InvalidFormat,
new DeserializationException( String.format( "Unable to deserialize request. " +
"Expected %s, found %s.", expectedTokens, foundTokens ) ) ) );
return false;
}
return true;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_transactional_StatementDeserializer.java
|
2,634
|
public class Statement
{
private final String statement;
private final Map<String, Object> parameters;
private final boolean includeStats;
private final ResultDataContent[] resultDataContents;
public Statement( String statement, Map<String, Object> parameters, boolean includeStats,
ResultDataContent... resultDataContents )
{
this.statement = statement;
this.parameters = parameters;
this.includeStats = includeStats;
this.resultDataContents = resultDataContents;
}
public String statement()
{
return statement;
}
public Map<String, Object> parameters()
{
return parameters;
}
public ResultDataContent[] resultDataContents()
{
return resultDataContents;
}
public boolean includeStats()
{
return includeStats;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_transactional_Statement.java
|
2,635
|
public class RowWriterTests
{
@Test
public void shouldWriteNestedMaps() throws Exception
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
JsonGenerator json = new JsonFactory(new Neo4jJsonCodec()).createJsonGenerator( out );
JsonNode row = serialize( out, json, new RowWriter( ) );
MatcherAssert.assertThat( row.size(), equalTo( 1 ) );
JsonNode firstCell = row.get( 0 );
MatcherAssert.assertThat( firstCell.get( "one" ).get( "two" ).size(), is( 2 ) );
MatcherAssert.assertThat( firstCell.get( "one" ).get( "two" ).get( 0 ).asBoolean(), is( true ) );
MatcherAssert.assertThat( firstCell.get( "one" ).get( "two" ).get( 1 ).get( "three" ).asInt(), is( 42 ) );
}
private JsonNode serialize( ByteArrayOutputStream out, JsonGenerator json, ResultDataContentWriter
resultDataContentWriter ) throws IOException, JsonParseException
{
json.writeStartObject();
// RETURN {one:{two:[true, {three: 42}]}}
resultDataContentWriter.write( json, asList( "the column" ), map( "the column", map( "one", map( "two",
asList( true,
map( "three", 42 ) ) ) ) ) );
json.writeEndObject();
json.flush();
json.close();
String jsonAsString = out.toString();
return jsonNode( jsonAsString ).get( "row" );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_transactional_RowWriterTests.java
|
2,636
|
class RowWriter implements ResultDataContentWriter
{
@Override
public void write( JsonGenerator out, Iterable<String> columns, Map<String, Object> row ) throws IOException
{
out.writeArrayFieldStart( "row" );
try
{
for ( String key : columns )
{
out.writeObject( row.get( key ) );
}
}
finally
{
out.writeEndArray();
}
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_transactional_RowWriter.java
|
2,637
|
rest
{
@Override
public ResultDataContentWriter writer( URI baseUri )
{
return new RestRepresentationWriter( baseUri );
}
};
| false
|
community_server_src_main_java_org_neo4j_server_rest_transactional_ResultDataContent.java
|
2,638
|
graph
{
@Override
public ResultDataContentWriter writer( URI baseUri )
{
return new GraphExtractionWriter();
}
},
| false
|
community_server_src_main_java_org_neo4j_server_rest_transactional_ResultDataContent.java
|
2,639
|
row
{
@Override
public ResultDataContentWriter writer( URI baseUri )
{
return new RowWriter();
}
},
| false
|
community_server_src_main_java_org_neo4j_server_rest_transactional_ResultDataContent.java
|
2,640
|
public class RestRepresentationWriterTests
{
@Test
public void shouldWriteNestedMaps() throws Exception
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
JsonGenerator json = new JsonFactory( new Neo4jJsonCodec() ).createJsonGenerator( out );
JsonNode rest = serialize( out, json, new RestRepresentationWriter( URI.create( "localhost" ) ) );
MatcherAssert.assertThat( rest.size(), equalTo( 1 ) );
JsonNode firstCell = rest.get( 0 );
MatcherAssert.assertThat( firstCell.get( "one" ).get( "two" ).size(), is( 2 ) );
MatcherAssert.assertThat( firstCell.get( "one" ).get( "two" ).get( 0 ).asBoolean(), is( true ) );
MatcherAssert.assertThat( firstCell.get( "one" ).get( "two" ).get( 1 ).get( "three" ).asInt(), is( 42 ) );
}
private JsonNode serialize( ByteArrayOutputStream out, JsonGenerator json, ResultDataContentWriter
resultDataContentWriter ) throws IOException, JsonParseException
{
json.writeStartObject();
// RETURN {one:{two:[true, {three: 42}]}}
resultDataContentWriter.write( json, asList( "the column" ), map( "the column", map( "one", map( "two",
asList( true,
map( "three", 42 ) ) ) ) ) );
json.writeEndObject();
json.flush();
json.close();
String jsonAsString = out.toString();
return jsonNode( jsonAsString ).get( "rest" );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_transactional_RestRepresentationWriterTests.java
|
2,641
|
class RestRepresentationWriter implements ResultDataContentWriter
{
private final URI baseUri;
RestRepresentationWriter( URI baseUri )
{
this.baseUri = baseUri;
}
@Override
public void write( JsonGenerator out, Iterable<String> columns, Map<String, Object> row ) throws IOException
{
RepresentationFormat format = new StreamingJsonFormat.StreamingRepresentationFormat( out, null );
out.writeArrayFieldStart( "rest" );
try
{
for ( String key : columns )
{
write( out, format, row.get( key ) );
}
}
finally
{
out.writeEndArray();
}
}
private void write( JsonGenerator out, RepresentationFormat format, Object value ) throws IOException
{
if ( value instanceof Map<?, ?> )
{
out.writeStartObject();
try
{
for ( Map.Entry<String, ?> entry : ((Map<String, ?>) value).entrySet() )
{
out.writeFieldName( entry.getKey() );
write( out, format, entry.getValue() );
}
}
finally
{
out.writeEndObject();
}
}
else if ( value instanceof Path )
{
write( format, new PathRepresentation<>( (Path) value ) );
}
else if ( value instanceof Iterable<?> )
{
out.writeStartArray();
try
{
for ( Object item : (Iterable<?>) value )
{
write( out, format, item );
}
}
finally
{
out.writeEndArray();
}
}
else if ( value instanceof Node )
{
write( format, new NodeRepresentation( (Node) value ) );
}
else if ( value instanceof Relationship )
{
write( format, new RelationshipRepresentation( (Relationship) value ) );
}
else
{
out.writeObject( value );
}
}
private void write( RepresentationFormat format, Representation representation )
{
OutputFormat.write( representation, format, baseUri );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_transactional_RestRepresentationWriter.java
|
2,642
|
public class Neo4jJsonCodec extends ObjectMapper
{
@Override
public void writeValue( JsonGenerator out, Object value ) throws IOException
{
if ( value instanceof PropertyContainer )
{
writePropertyContainer( out, (PropertyContainer) value );
}
else if ( value instanceof Path )
{
writePath( out, ((Path) value).iterator() );
}
else if (value instanceof Iterable)
{
writeIterator( out, ((Iterable) value).iterator() );
}
else if ( value instanceof byte[] )
{
writeByteArray( out, (byte[]) value );
}
else if ( value instanceof Map )
{
writeMap(out, (Map) value );
}
else
{
super.writeValue( out, value );
}
}
private void writeMap( JsonGenerator out, Map value ) throws IOException
{
out.writeStartObject();
Set<Map.Entry> set = value.entrySet();
for ( Map.Entry e : set )
{
out.writeFieldName( e.getKey().toString() );
writeValue( out, e.getValue() );
}
out.writeEndObject();
}
private void writeIterator( JsonGenerator out, Iterator value ) throws IOException
{
out.writeStartArray();
while ( value.hasNext() )
{
writeValue( out, value.next() );
}
out.writeEndArray();
}
private void writePath( JsonGenerator out, Iterator<PropertyContainer> value ) throws IOException
{
out.writeStartArray();
while ( value.hasNext() )
{
writePropertyContainer( out, value.next() );
}
out.writeEndArray();
}
private void writePropertyContainer( JsonGenerator out, PropertyContainer value ) throws IOException
{
out.writeStartObject();
for ( String key : value.getPropertyKeys() )
{
out.writeObjectField( key, value.getProperty( key ) );
}
out.writeEndObject();
}
private void writeByteArray( JsonGenerator out, byte[] bytes ) throws IOException
{
out.writeStartArray();
for ( byte b : bytes )
{
out.writeNumber( (int) b );
}
out.writeEndArray();
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_transactional_Neo4jJsonCodec.java
|
2,643
|
public class GraphExtractionWriterTest
{
private final Node n1 = node( 17, properties( property( "name", "n1" ) ), "Foo" );
private final Node n2 = node( 666, properties( property( "name", "n2" ) ) );
private final Node n3 = node( 42, properties( property( "name", "n3" ) ), "Foo", "Bar" );
private final Relationship r1 = relationship( 7, n1, "ONE", n2, property( "name", "r1" ) );
private final Relationship r2 = relationship( 8, n1, "TWO", n3, property( "name", "r2" ) );
@Test
public void shouldExtractNodesFromRow() throws Exception
{
// given
Map<String, Object> row = new HashMap<>();
row.put( "n1", n1 );
row.put( "n2", n2 );
row.put( "n3", n3 );
row.put( "other.thing", "hello" );
row.put( "some.junk", 0x0099cc );
// when
JsonNode result = write( row );
// then
assertNodes( result );
assertEquals( "there should be no relationships", 0, result.get( "graph" ).get( "relationships" ).size() );
}
@Test
public void shouldExtractRelationshipsFromRowAndNodesFromRelationships() throws Exception
{
// given
Map<String, Object> row = new HashMap<>();
row.put( "r1", r1 );
row.put( "r2", r2 );
// when
JsonNode result = write( row );
// then
assertNodes( result );
assertRelationships( result );
}
@Test
public void shouldExtractPathFromRowAndExtractNodesAndRelationshipsFromPath() throws Exception
{
// given
Map<String, Object> row = new HashMap<>();
row.put( "p", path( n2, link( r1, n1 ), link( r2, n3 ) ) );
// when
JsonNode result = write( row );
// then
assertNodes( result );
assertRelationships( result );
}
@Test
public void shouldExtractGraphFromMapInTheRow() throws Exception
{
// given
Map<String, Object> row = new HashMap<>(), map = new HashMap<>();
row.put( "map", map );
map.put( "r1", r1 );
map.put( "r2", r2 );
// when
JsonNode result = write( row );
// then
assertNodes( result );
assertRelationships( result );
}
@Test
public void shouldExtractGraphFromListInTheRow() throws Exception
{
// given
Map<String, Object> row = new HashMap<>();
List<Object> list = new ArrayList<>();
row.put( "list", list );
list.add( r1 );
list.add( r2 );
// when
JsonNode result = write( row );
// then
assertNodes( result );
assertRelationships( result );
}
@Test
public void shouldExtractGraphFromListInMapInTheRow() throws Exception
{
// given
Map<String, Object> row = new HashMap<>(), map = new HashMap<>();
List<Object> list = new ArrayList<>();
map.put( "list", list );
row.put( "map", map );
list.add( r1 );
list.add( r2 );
// when
JsonNode result = write( row );
// then
assertNodes( result );
assertRelationships( result );
}
@Test
public void shouldExtractGraphFromMapInListInTheRow() throws Exception
{
// given
Map<String, Object> row = new HashMap<>(), map = new HashMap<>();
List<Object> list = new ArrayList<>();
list.add( map );
row.put( "list", list );
map.put( "r1", r1 );
map.put( "r2", r2 );
// when
JsonNode result = write( row );
// then
assertNodes( result );
assertRelationships( result );
}
// The code under test
private JsonFactory jsonFactory = new JsonFactory();
private JsonNode write( Map<String, Object> row ) throws IOException, JsonParseException
{
ByteArrayOutputStream out = new ByteArrayOutputStream();
JsonGenerator json = jsonFactory.createJsonGenerator( out );
json.writeStartObject();
try
{
new GraphExtractionWriter().write( json, null, row );
}
finally
{
json.writeEndObject();
json.flush();
}
return JsonHelper.jsonNode( out.toString( "UTF-8" ) );
}
// The expected format of the result
private void assertNodes( JsonNode result )
{
JsonNode nodes = result.get( "graph" ).get( "nodes" );
assertEquals( "there should be 3 nodes", 3, nodes.size() );
assertNode( "17", nodes, asList( "Foo" ), property( "name", "n1" ) );
assertNode( "666", nodes, Arrays.<String>asList(), property( "name", "n2" ) );
assertNode( "42", nodes, asList( "Foo", "Bar" ), property( "name", "n3" ) );
}
private void assertRelationships( JsonNode result )
{
JsonNode relationships = result.get( "graph" ).get( "relationships" );
assertEquals( "there should be 2 relationships", 2, relationships.size() );
assertRelationship( "7", relationships, "17", "ONE", "666", property( "name", "r1" ) );
assertRelationship( "8", relationships, "17", "TWO", "42", property( "name", "r2" ) );
}
// Helpers
private static void assertNode( String id, JsonNode nodes, List<String> labels, Property... properties )
{
JsonNode node = get( nodes, id );
assertListEquals( "Node[" + id + "].labels", labels, node.get( "labels" ) );
JsonNode props = node.get( "properties" );
assertEquals( "length( Node[" + id + "].properties )", properties.length, props.size() );
for ( Property property : properties )
{
assertJsonEquals( "Node[" + id + "].properties[" + property.key() + "]",
property.value(), props.get( property.key() ) );
}
}
private static void assertRelationship( String id, JsonNode relationships, String startNodeId, String type,
String endNodeId, Property... properties )
{
JsonNode relationship = get( relationships, id );
assertEquals( "Relationship[" + id + "].labels", type, relationship.get( "type" ).getTextValue() );
assertEquals( "Relationship[" + id + "].startNode", startNodeId,
relationship.get( "startNode" ).getTextValue() );
assertEquals( "Relationship[" + id + "].endNode", endNodeId, relationship.get( "endNode" ).getTextValue() );
JsonNode props = relationship.get( "properties" );
assertEquals( "length( Relationship[" + id + "].properties )", properties.length, props.size() );
for ( Property property : properties )
{
assertJsonEquals( "Relationship[" + id + "].properties[" + property.key() + "]",
property.value(), props.get( property.key() ) );
}
}
private static void assertJsonEquals( String message, Object expected, JsonNode actual )
{
if ( expected == null )
{
assertTrue( message, actual == null || actual.isNull() );
}
else if ( expected instanceof String )
{
assertEquals( message, expected, actual.getTextValue() );
}
else if ( expected instanceof Number )
{
assertEquals( message, expected, actual.getNumberValue() );
}
else
{
fail( message + " - unexpected type - " + expected );
}
}
private static void assertListEquals( String what, List<String> expected, JsonNode jsonNode )
{
assertTrue( what + " - should be a list", jsonNode.isArray() );
List<String> actual = new ArrayList<>( jsonNode.size() );
for ( JsonNode node : jsonNode )
{
actual.add( node.getTextValue() );
}
assertEquals( what, expected, actual );
}
private static JsonNode get( Iterable<JsonNode> jsonNodes, String id )
{
for ( JsonNode jsonNode : jsonNodes )
{
if ( id.equals( jsonNode.get( "id" ).getTextValue() ) )
{
return jsonNode;
}
}
return null;
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_transactional_GraphExtractionWriterTest.java
|
2,644
|
class GraphExtractionWriter implements ResultDataContentWriter
{
@Override
public void write( JsonGenerator out, Iterable<String> columns, Map<String, Object> row ) throws IOException
{
Set<Node> nodes = new HashSet<>();
Set<Relationship> relationships = new HashSet<>();
extract( nodes, relationships, row.values() );
out.writeObjectFieldStart( "graph" );
try
{
writeNodes( out, nodes );
writeRelationships( out, relationships );
}
finally
{
out.writeEndObject();
}
}
private void writeNodes( JsonGenerator out, Iterable<Node> nodes ) throws IOException
{
out.writeArrayFieldStart( "nodes" );
try
{
for ( Node node : nodes )
{
out.writeStartObject();
try
{
out.writeStringField( "id", Long.toString( node.getId() ) );
out.writeArrayFieldStart( "labels" );
try
{
for ( Label label : node.getLabels() )
{
out.writeString( label.name() );
}
}
finally
{
out.writeEndArray();
}
writeProperties( out, node );
}
finally
{
out.writeEndObject();
}
}
}
finally
{
out.writeEndArray();
}
}
private void writeRelationships( JsonGenerator out, Iterable<Relationship> relationships ) throws IOException
{
out.writeArrayFieldStart( "relationships" );
try
{
for ( Relationship relationship : relationships )
{
out.writeStartObject();
try
{
out.writeStringField( "id", Long.toString( relationship.getId() ) );
out.writeStringField( "type", relationship.getType().name() );
out.writeStringField( "startNode", Long.toString( relationship.getStartNode().getId() ) );
out.writeStringField( "endNode", Long.toString( relationship.getEndNode().getId() ) );
writeProperties( out, relationship );
}
finally
{
out.writeEndObject();
}
}
}
finally
{
out.writeEndArray();
}
}
private void writeProperties( JsonGenerator out, PropertyContainer container ) throws IOException
{
out.writeObjectFieldStart( "properties" );
try
{
for ( String key : container.getPropertyKeys() )
{
out.writeObjectField( key, container.getProperty( key ) );
}
}
finally
{
out.writeEndObject();
}
}
private void extract( Set<Node> nodes, Set<Relationship> relationships, Iterable<?> source )
{
for ( Object item : source )
{
if ( item instanceof Node )
{
nodes.add( (Node) item );
}
else if ( item instanceof Relationship )
{
Relationship relationship = (Relationship) item;
relationships.add( relationship );
nodes.add( relationship.getStartNode() );
nodes.add( relationship.getEndNode() );
}
if ( item instanceof Path )
{
Path path = (Path) item;
for ( Node node : path.nodes() )
{
nodes.add( node );
}
for ( Relationship relationship : path.relationships() )
{
relationships.add( relationship );
}
}
else if ( item instanceof Map<?, ?> )
{
extract( nodes, relationships, ((Map<?, ?>) item).values() );
}
else if ( item instanceof Iterable<?> )
{
extract( nodes, relationships, (Iterable<?>) item );
}
}
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_transactional_GraphExtractionWriter.java
|
2,645
|
{
@Override
public void close()
{
}
@Override
public boolean hasNext()
{
return inner.hasNext();
}
@Override
public Map<String, Object> next()
{
return inner.next();
}
@Override
public void remove()
{
inner.remove();
}
};
| false
|
community_server_src_test_java_org_neo4j_server_rest_transactional_ExecutionResultSerializerTest.java
|
2,646
|
public class ExecutionResultSerializerTest
{
@Test
public void shouldSerializeResponseWithCommitUriOnly() throws Exception
{
// given
ByteArrayOutputStream output = new ByteArrayOutputStream();
ExecutionResultSerializer serializer = new ExecutionResultSerializer( output, null, org.neo4j.kernel.impl.util
.StringLogger.DEV_NULL );
// when
serializer.transactionCommitUri( URI.create( "commit/uri/1" ) );
serializer.finish();
// then
String result = output.toString( "UTF-8" );
assertEquals( "{\"commit\":\"commit/uri/1\",\"results\":[],\"errors\":[]}", result );
}
@Test
public void shouldSerializeResponseWithCommitUriAndResults() throws Exception
{
// given
ByteArrayOutputStream output = new ByteArrayOutputStream();
ExecutionResultSerializer serializer = new ExecutionResultSerializer( output, null, StringLogger.DEV_NULL );
ExecutionResult executionResult = mockExecutionResult( map(
"column1", "value1",
"column2", "value2" ) );
// when
serializer.transactionCommitUri( URI.create( "commit/uri/1" ) );
serializer.statementResult( executionResult, false );
serializer.finish();
// then
String result = output.toString( "UTF-8" );
assertEquals( "{\"commit\":\"commit/uri/1\",\"results\":[{\"columns\":[\"column1\",\"column2\"]," +
"\"data\":[{\"row\":[\"value1\",\"value2\"]}]}],\"errors\":[]}", result );
}
@Test
public void shouldSerializeResponseWithResultsOnly() throws Exception
{
// given
ByteArrayOutputStream output = new ByteArrayOutputStream();
ExecutionResultSerializer serializer = new ExecutionResultSerializer( output, null, StringLogger.DEV_NULL );
ExecutionResult executionResult = mockExecutionResult( map(
"column1", "value1",
"column2", "value2" ) );
// when
serializer.statementResult( executionResult, false );
serializer.finish();
// then
String result = output.toString( "UTF-8" );
assertEquals( "{\"results\":[{\"columns\":[\"column1\",\"column2\"]," +
"\"data\":[{\"row\":[\"value1\",\"value2\"]}]}],\"errors\":[]}", result );
}
@Test
public void shouldSerializeResponseWithCommitUriAndResultsAndErrors() throws Exception
{
// given
ByteArrayOutputStream output = new ByteArrayOutputStream();
ExecutionResultSerializer serializer = new ExecutionResultSerializer( output, null, StringLogger.DEV_NULL );
ExecutionResult executionResult = mockExecutionResult( map(
"column1", "value1",
"column2", "value2" ) );
// when
serializer.transactionCommitUri( URI.create( "commit/uri/1" ) );
serializer.statementResult( executionResult, false );
serializer.errors( asList( new Neo4jError( Status.Request.InvalidFormat, new Exception( "cause1" ) ) ) );
serializer.finish();
// then
String result = output.toString( "UTF-8" );
assertEquals( "{\"commit\":\"commit/uri/1\",\"results\":[{\"columns\":[\"column1\",\"column2\"]," +
"\"data\":[{\"row\":[\"value1\",\"value2\"]}]}]," +
"\"errors\":[{\"code\":\"Neo.ClientError.Request.InvalidFormat\",\"message\":\"cause1\"}]}",
result );
}
@Test
public void shouldSerializeResponseWithResultsAndErrors() throws Exception
{
// given
ByteArrayOutputStream output = new ByteArrayOutputStream();
ExecutionResultSerializer serializer = new ExecutionResultSerializer( output, null, StringLogger.DEV_NULL );
ExecutionResult executionResult = mockExecutionResult( map(
"column1", "value1",
"column2", "value2" ) );
// when
serializer.statementResult( executionResult, false );
serializer.errors( asList( new Neo4jError( Status.Request.InvalidFormat, new Exception( "cause1" ) ) ) );
serializer.finish();
// then
String result = output.toString( "UTF-8" );
assertEquals( "{\"results\":[{\"columns\":[\"column1\",\"column2\"]," +
"\"data\":[{\"row\":[\"value1\",\"value2\"]}]}]," +
"\"errors\":[{\"code\":\"Neo.ClientError.Request.InvalidFormat\",\"message\":\"cause1\"}]}",
result );
}
@Test
public void shouldSerializeResponseWithCommitUriAndErrors() throws Exception
{
// given
ByteArrayOutputStream output = new ByteArrayOutputStream();
ExecutionResultSerializer serializer = new ExecutionResultSerializer( output, null, StringLogger.DEV_NULL );
// when
serializer.transactionCommitUri( URI.create( "commit/uri/1" ) );
serializer.errors( asList( new Neo4jError( Status.Request.InvalidFormat, new Exception( "cause1" ) ) ) );
serializer.finish();
// then
String result = output.toString( "UTF-8" );
assertEquals( "{\"commit\":\"commit/uri/1\",\"results\":[],\"errors\":[{\"code\":\"Neo.ClientError.Request.InvalidFormat\"," +
"\"message\":\"cause1\"}]}", result );
}
@Test
public void shouldSerializeResponseWithErrorsOnly() throws Exception
{
// given
ByteArrayOutputStream output = new ByteArrayOutputStream();
ExecutionResultSerializer serializer = new ExecutionResultSerializer( output, null, StringLogger.DEV_NULL );
// when
serializer.errors( asList( new Neo4jError( Status.Request.InvalidFormat, new Exception( "cause1" ) ) ) );
serializer.finish();
// then
String result = output.toString( "UTF-8" );
assertEquals(
"{\"results\":[],\"errors\":[{\"code\":\"Neo.ClientError.Request.InvalidFormat\",\"message\":\"cause1\"}]}",
result );
}
@Test
public void shouldSerializeResponseWithNoCommitUriResultsOrErrors() throws Exception
{
// given
ByteArrayOutputStream output = new ByteArrayOutputStream();
ExecutionResultSerializer serializer = new ExecutionResultSerializer( output, null, StringLogger.DEV_NULL );
// when
serializer.finish();
// then
String result = output.toString( "UTF-8" );
assertEquals( "{\"results\":[],\"errors\":[]}", result );
}
@Test
public void shouldSerializeResponseWithMultipleResultRows() throws Exception
{
// given
ByteArrayOutputStream output = new ByteArrayOutputStream();
ExecutionResultSerializer serializer = new ExecutionResultSerializer( output, null, StringLogger.DEV_NULL );
ExecutionResult executionResult = mockExecutionResult( map(
"column1", "value1",
"column2", "value2" ), map(
"column1", "value3",
"column2", "value4" ) );
// when
serializer.statementResult( executionResult, false );
serializer.finish();
// then
String result = output.toString( "UTF-8" );
assertEquals( "{\"results\":[{\"columns\":[\"column1\",\"column2\"]," +
"\"data\":[{\"row\":[\"value1\",\"value2\"]},{\"row\":[\"value3\",\"value4\"]}]}]," +
"\"errors\":[]}", result );
}
@Test
public void shouldSerializeResponseWithMultipleResults() throws Exception
{
// given
ByteArrayOutputStream output = new ByteArrayOutputStream();
ExecutionResultSerializer serializer = new ExecutionResultSerializer( output, null, StringLogger.DEV_NULL );
ExecutionResult executionResult1 = mockExecutionResult( map(
"column1", "value1",
"column2", "value2" ) );
ExecutionResult executionResult2 = mockExecutionResult( map(
"column3", "value3",
"column4", "value4" ) );
// when
serializer.statementResult( executionResult1, false );
serializer.statementResult( executionResult2, false );
serializer.finish();
// then
String result = output.toString( "UTF-8" );
assertEquals( "{\"results\":[" +
"{\"columns\":[\"column1\",\"column2\"],\"data\":[{\"row\":[\"value1\",\"value2\"]}]}," +
"{\"columns\":[\"column3\",\"column4\"],\"data\":[{\"row\":[\"value3\",\"value4\"]}]}]," +
"\"errors\":[]}", result );
}
@Test
public void shouldSerializeNodeAsMapOfProperties() throws Exception
{
// given
ByteArrayOutputStream output = new ByteArrayOutputStream();
ExecutionResultSerializer serializer = new ExecutionResultSerializer( output, null, StringLogger.DEV_NULL );
ExecutionResult executionResult = mockExecutionResult( map(
"node", node( 1, properties(
property( "a", 12 ),
property( "b", true ),
property( "c", new int[]{1, 0, 1, 2} ),
property( "d", new byte[]{1, 0, 1, 2} ),
property( "e", new String[]{"a", "b", "ääö"} ) ) ) ) );
// when
serializer.statementResult( executionResult, false );
serializer.finish();
// then
String result = output.toString( "UTF-8" );
assertEquals( "{\"results\":[{\"columns\":[\"node\"]," +
"\"data\":[{\"row\":[{\"d\":[1,0,1,2],\"e\":[\"a\",\"b\",\"ääö\"],\"b\":true,\"c\":[1,0,1,2],\"a\":12}]}]}]," +
"\"errors\":[]}", result );
}
@Test
public void shouldSerializeNestedEntities() throws Exception
{
// given
ByteArrayOutputStream output = new ByteArrayOutputStream();
ExecutionResultSerializer serializer = new ExecutionResultSerializer( output, null, StringLogger.DEV_NULL );
Node a = node( 1, properties( property( "foo", 12 ) ) );
Node b = node( 2, properties( property( "bar", false ) ) );
Relationship r = relationship( 1, properties( property( "baz", "quux" ) ), a, "FRAZZLE", b );
ExecutionResult executionResult = mockExecutionResult( map(
"nested", map(
"node", a,
"edge", r,
"path", path( a, link(r, b) )
) ) );
// when
serializer.statementResult( executionResult, false );
serializer.finish();
// then
String result = output.toString( "UTF-8" );
assertEquals( "{\"results\":[{\"columns\":[\"nested\"]," +
"\"data\":[{\"row\":[{\"node\":{\"foo\":12},\"edge\":{\"baz\":\"quux\"},\"path\":[{\"foo\":12},{\"baz\":\"quux\"},{\"bar\":false}]}]}]}]," +
"\"errors\":[]}", result );
}
@Test
public void shouldSerializePathAsListOfMapsOfProperties() throws Exception
{
// given
ByteArrayOutputStream output = new ByteArrayOutputStream();
ExecutionResultSerializer serializer = new ExecutionResultSerializer( output, null, StringLogger.DEV_NULL );
ExecutionResult executionResult = mockExecutionResult( map(
"path", mockPath( map( "key1", "value1" ), map( "key2", "value2" ), map( "key3", "value3" ) ) ) );
// when
serializer.statementResult( executionResult, false );
serializer.finish();
// then
String result = output.toString( "UTF-8" );
assertEquals( "{\"results\":[{\"columns\":[\"path\"]," +
"\"data\":[{\"row\":[[{\"key1\":\"value1\"},{\"key2\":\"value2\"},{\"key3\":\"value3\"}]]}]}]," +
"\"errors\":[]}", result );
}
@Test
public void shouldProduceWellFormedJsonEvenIfResultIteratorThrowsExceptionOnNext() throws Exception
{
// given
ByteArrayOutputStream output = new ByteArrayOutputStream();
ExecutionResultSerializer serializer = new ExecutionResultSerializer( output, null, StringLogger.DEV_NULL );
Map<String, Object> data = map(
"column1", "value1",
"column2", "value2" );
ExecutionResult executionResult = mock( ExecutionResult.class );
when( executionResult.columns() ).thenReturn( new ArrayList<>( data.keySet() ) );
@SuppressWarnings("unchecked")
ResourceIterator<Map<String, Object>> iterator = mock( ResourceIterator.class );
when( iterator.hasNext() ).thenReturn( true, true, false );
when( iterator.next() ).thenReturn( data ).thenThrow( new RuntimeException( "Stuff went wrong!" ) );
when( executionResult.iterator() ).thenReturn( iterator );
// when
try
{
serializer.statementResult( executionResult, false );
fail( "should have thrown exception" );
}
catch ( RuntimeException e )
{
serializer.errors( asList( new Neo4jError( Status.Statement.ExecutionFailure, e ) ) );
}
serializer.finish();
// then
String result = output.toString( "UTF-8" );
assertEquals(
"{\"results\":[{\"columns\":[\"column1\",\"column2\"],\"data\":[{\"row\":[\"value1\",\"value2\"]}]}]," +
"\"errors\":[{\"code\":\"Neo.DatabaseError.Statement.ExecutionFailure\",\"message\":\"Stuff went wrong!\",\"stackTrace\":***}]}",
replaceStackTrace( result, "***" ) );
}
@Test
public void shouldProduceWellFormedJsonEvenIfResultIteratorThrowsExceptionOnHasNext() throws Exception
{
// given
ByteArrayOutputStream output = new ByteArrayOutputStream();
ExecutionResultSerializer serializer = new ExecutionResultSerializer( output, null, StringLogger.DEV_NULL );
Map<String, Object> data = map(
"column1", "value1",
"column2", "value2" );
ExecutionResult executionResult = mock( ExecutionResult.class );
when( executionResult.columns() ).thenReturn( new ArrayList<>( data.keySet() ) );
@SuppressWarnings("unchecked")
ResourceIterator<Map<String, Object>> iterator = mock( ResourceIterator.class );
when( iterator.hasNext() ).thenReturn( true ).thenThrow(
new RuntimeException( "Stuff went wrong!" ) );
when( iterator.next() ).thenReturn( data );
when( executionResult.iterator() ).thenReturn( iterator );
// when
try
{
serializer.statementResult( executionResult, false );
fail( "should have thrown exception" );
}
catch ( RuntimeException e )
{
serializer.errors( asList( new Neo4jError( Status.Statement.ExecutionFailure, e ) ) );
}
serializer.finish();
// then
String result = output.toString( "UTF-8" );
assertEquals(
"{\"results\":[{\"columns\":[\"column1\",\"column2\"],\"data\":[{\"row\":[\"value1\",\"value2\"]}]}]," +
"\"errors\":[{\"code\":\"Neo.DatabaseError.Statement.ExecutionFailure\",\"message\":\"Stuff went wrong!\"," +
"\"stackTrace\":***}]}",
replaceStackTrace( result, "***" ) );
}
@Test
public void shouldProduceResultStreamWithGraphEntries() throws Exception
{
// given
Node[] node = {
node( 0, properties( property( "name", "node0" ) ), "Node" ),
node( 1, properties( property( "name", "node1" ) ) ),
node( 2, properties( property( "name", "node2" ) ), "This", "That" ),
node( 3, properties( property( "name", "node3" ) ), "Other" )};
Relationship[] rel = {
relationship( 0, node[0], "KNOWS", node[1], property( "name", "rel0" ) ),
relationship( 1, node[2], "LOVES", node[3], property( "name", "rel1" ) )};
ByteArrayOutputStream output = new ByteArrayOutputStream();
ExecutionResultSerializer serializer = new ExecutionResultSerializer( output, null, StringLogger.DEV_NULL );
// when
serializer.statementResult( mockExecutionResult(
map( "node", node[0], "rel", rel[0] ),
map( "node", node[2], "rel", rel[1] ) ), false, ResultDataContent.row, ResultDataContent.graph );
serializer.finish();
// then
String result = output.toString( "UTF-8" );
// Nodes and relationships form sets, so we cannot test for a fixed string, since we don't know the order.
String node0 = "{\"id\":\"0\",\"labels\":[\"Node\"],\"properties\":{\"name\":\"node0\"}}";
String node1 = "{\"id\":\"1\",\"labels\":[],\"properties\":{\"name\":\"node1\"}}";
String node2 = "{\"id\":\"2\",\"labels\":[\"This\",\"That\"],\"properties\":{\"name\":\"node2\"}}";
String node3 = "{\"id\":\"3\",\"labels\":[\"Other\"],\"properties\":{\"name\":\"node3\"}}";
String rel0 = "\"relationships\":[{\"id\":\"0\",\"type\":\"KNOWS\",\"startNode\":\"0\",\"endNode\":\"1\",\"properties\":{\"name\":\"rel0\"}}]}";
String rel1 = "\"relationships\":[{\"id\":\"1\",\"type\":\"LOVES\",\"startNode\":\"2\",\"endNode\":\"3\",\"properties\":{\"name\":\"rel1\"}}]}";
String row0 = "{\"row\":[{\"name\":\"node0\"},{\"name\":\"rel0\"}],\"graph\":{\"nodes\":[";
String row1 = "{\"row\":[{\"name\":\"node2\"},{\"name\":\"rel1\"}],\"graph\":{\"nodes\":[";
int n0 = result.indexOf( node0 );
int n1 = result.indexOf( node1 );
int n2 = result.indexOf( node2 );
int n3 = result.indexOf( node3 );
int r0 = result.indexOf( rel0 );
int r1 = result.indexOf( rel1 );
int _0 = result.indexOf( row0 );
int _1 = result.indexOf( row1 );
assertTrue( "result should contain row0", _0 > 0 );
assertTrue( "result should contain row1 after row0", _1 > _0 );
assertTrue( "result should contain node0 after row0", n0 > _0 );
assertTrue( "result should contain node1 after row0", n1 > _0 );
assertTrue( "result should contain node2 after row1", n2 > _1 );
assertTrue( "result should contain node3 after row1", n3 > _1 );
assertTrue( "result should contain rel0 after node0 and node1", r0 > n0 && r0 > n1 );
assertTrue( "result should contain rel1 after node2 and node3", r1 > n2 && r1 > n3 );
}
@Test
public void shouldProduceResultStreamWithLegacyRestFormat() throws Exception
{
// given
Node[] node = {
node( 0, properties( property( "name", "node0" ) ) ),
node( 1, properties( property( "name", "node1" ) ) ),
node( 2, properties( property( "name", "node2" ) ) )};
Relationship[] rel = {
relationship( 0, node[0], "KNOWS", node[1], property( "name", "rel0" ) ),
relationship( 1, node[2], "LOVES", node[1], property( "name", "rel1" ) )};
Path path = GraphMock.path( node[0], link( rel[0], node[1] ), link( rel[1], node[2] ) );
ByteArrayOutputStream output = new ByteArrayOutputStream();
ExecutionResultSerializer serializer = new ExecutionResultSerializer(
output, URI.create( "http://base.uri/" ), StringLogger.DEV_NULL );
// when
serializer.statementResult( mockExecutionResult(
map( "node", node[0], "rel", rel[0], "path", path, "map", map( "n1", node[1], "r1", rel[1] ) )
), false, ResultDataContent.rest );
serializer.finish();
// then
String result = output.toString( "UTF-8" );
JsonNode json = jsonNode( result );
Map<String, Integer> columns = new HashMap<>();
int col = 0;
JsonNode results = json.get( "results" ).get( 0 );
for ( JsonNode column : results.get( "columns" ) )
{
columns.put( column.getTextValue(), col++ );
}
JsonNode row = results.get( "data" ).get( 0 ).get( "rest" );
JsonNode jsonNode = row.get( columns.get( "node" ) );
JsonNode jsonRel = row.get( columns.get( "rel" ) );
JsonNode jsonPath = row.get( columns.get( "path" ) );
JsonNode jsonMap = row.get( columns.get( "map" ) );
assertEquals( "http://base.uri/node/0", jsonNode.get( "self" ).getTextValue() );
assertEquals( "http://base.uri/relationship/0", jsonRel.get( "self" ).getTextValue() );
assertEquals( 2, jsonPath.get( "length" ).getNumberValue() );
assertEquals( "http://base.uri/node/0", jsonPath.get( "start" ).getTextValue() );
assertEquals( "http://base.uri/node/2", jsonPath.get( "end" ).getTextValue() );
assertEquals( "http://base.uri/node/1", jsonMap.get( "n1" ).get( "self" ).getTextValue() );
assertEquals( "http://base.uri/relationship/1", jsonMap.get( "r1" ).get( "self" ).getTextValue() );
}
@Test
public void shouldProduceResultStreamWithLegacyRestFormatAndNestedMaps() throws Exception
{
// given
ByteArrayOutputStream output = new ByteArrayOutputStream();
ExecutionResultSerializer serializer = new ExecutionResultSerializer(
output, URI.create( "http://base.uri/" ), StringLogger.DEV_NULL );
// when
serializer.statementResult( mockExecutionResult(
// RETURN {one:{two:['wait for it...', {three: 'GO!'}]}}
map( "map", map("one", map( "two", asList("wait for it...", map("three", "GO!") ) ) ) )
), false, ResultDataContent.rest );
serializer.finish();
// then
String result = output.toString( "UTF-8" );
JsonNode json = jsonNode( result );
Map<String, Integer> columns = new HashMap<>();
int col = 0;
JsonNode results = json.get( "results" ).get( 0 );
for ( JsonNode column : results.get( "columns" ) )
{
columns.put( column.getTextValue(), col++ );
}
JsonNode row = results.get( "data" ).get( 0 ).get( "rest" );
JsonNode jsonMap = row.get( columns.get( "map" ) );
assertEquals( "wait for it...", jsonMap.get( "one" ).get( "two" ).get( 0 ).asText() );
assertEquals( "GO!", jsonMap.get( "one" ).get( "two" ).get( 1 ).get( "three" ).asText() );
}
@Test
public void shouldLogIOErrors() throws Exception
{
// given
IOException failure = new IOException();
OutputStream output = mock( OutputStream.class, new ThrowsException( failure ) );
TestLogger log = new TestLogger();
ExecutionResultSerializer serializer = new ExecutionResultSerializer( output, null, log );
// when
serializer.finish();
// then
log.assertExactly( error( "Failed to generate JSON output.", failure ) );
}
@SafeVarargs
private static ExecutionResult mockExecutionResult( Map<String, Object>... rows )
{
Set<String> keys = new HashSet<>();
for ( Map<String, Object> row : rows )
{
keys.addAll( row.keySet() );
}
ExecutionResult executionResult = mock( ExecutionResult.class );
when( executionResult.columns() ).thenReturn( new ArrayList<>( keys ) );
final Iterator<Map<String, Object>> inner = asList( rows ).iterator();
ResourceIterator<Map<String, Object>> iterator = new ResourceIterator<Map<String, Object>>()
{
@Override
public void close()
{
}
@Override
public boolean hasNext()
{
return inner.hasNext();
}
@Override
public Map<String, Object> next()
{
return inner.next();
}
@Override
public void remove()
{
inner.remove();
}
};
when( executionResult.iterator() ).thenReturn( iterator );
return executionResult;
}
private static Path mockPath( Map<String, Object> startNodeProperties, Map<String, Object> relationshipProperties,
Map<String,Object> endNodeProperties )
{
Node startNode = node( 1, properties( startNodeProperties ) );
Node endNode = node( 2, properties( endNodeProperties ) );
Relationship relationship = relationship( 1, properties( relationshipProperties ),
startNode, "RELATED", endNode );
return path( startNode, Link.link( relationship, endNode ) );
}
private String replaceStackTrace( String json, String matchableStackTrace )
{
return json.replaceAll( "\"stackTrace\":\"[^\"]*\"", "\"stackTrace\":" + matchableStackTrace );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_transactional_ExecutionResultSerializerTest.java
|
2,647
|
public class ExecutionResultSerializer
{
public ExecutionResultSerializer( OutputStream output, URI baseUri, StringLogger log )
{
this.baseUri = baseUri;
this.log = log;
JsonGenerator generator = null;
try
{
generator = JSON_FACTORY.createJsonGenerator( output );
}
catch ( IOException e )
{
loggedIOException( e );
}
this.out = generator;
}
/**
* Will always get called at most once once, and is the first method to get called. This method is not allowed
* to throw exceptions. If there are network errors or similar, the handler should take appropriate action,
* but never fail this method.
*/
public void transactionCommitUri( URI commitUri )
{
try
{
ensureDocumentOpen();
out.writeStringField( "commit", commitUri.toString() );
}
catch ( IOException e )
{
loggedIOException( e );
}
}
/**
* Will get called at most once per statement. Throws IOException so that upstream executor can decide whether
* to execute further statements.
*/
public void statementResult( ExecutionResult result, boolean includeStats, ResultDataContent... resultDataContents )
throws IOException
{
try
{
ensureResultsFieldOpen();
out.writeStartObject();
try
{
Iterable<String> columns = result.columns();
writeColumns( columns );
writeRows( columns, result.iterator(), configureWriters( resultDataContents ) );
if ( includeStats )
{
writeStats( result.getQueryStatistics() );
}
}
finally
{
out.writeEndObject(); // </result>
}
}
catch ( IOException e )
{
throw loggedIOException( e );
}
}
private void writeStats( QueryStatistics stats ) throws IOException
{
out.writeObjectFieldStart( "stats" );
try
{
out.writeBooleanField( "contains_updates", stats.containsUpdates() );
out.writeNumberField( "nodes_created", stats.getNodesCreated() );
out.writeNumberField( "nodes_deleted", stats.getDeletedNodes() );
out.writeNumberField( "properties_set", stats.getPropertiesSet() );
out.writeNumberField( "relationships_created", stats.getRelationshipsCreated() );
out.writeNumberField( "relationship_deleted", stats.getDeletedRelationships() );
out.writeNumberField( "labels_added", stats.getLabelsAdded() );
out.writeNumberField( "labels_removed", stats.getLabelsRemoved() );
out.writeNumberField( "indexes_added", stats.getIndexesAdded() );
out.writeNumberField( "indexes_removed", stats.getIndexesRemoved() );
out.writeNumberField( "constraints_added", stats.getConstraintsAdded() );
out.writeNumberField( "constraints_removed", stats.getConstraintsRemoved() );
}
finally
{
out.writeEndObject();
}
}
/**
* Will get called once if any errors occurred, after {@link #statementResult(org.neo4j.cypher.javacompat.ExecutionResult, boolean, ResultDataContent...)} statementResults}
* has been called This method is not allowed to throw exceptions. If there are network errors or similar, the
* handler should take appropriate action, but never fail this method.
*/
public void errors( Iterable<? extends Neo4jError> errors )
{
try
{
ensureDocumentOpen();
ensureResultsFieldClosed();
out.writeArrayFieldStart( "errors" );
try
{
for ( Neo4jError error : errors )
{
try
{
out.writeStartObject();
out.writeObjectField( "code", error.status().code().serialize() );
out.writeObjectField( "message", error.getMessage() );
if ( error.shouldSerializeStackTrace() )
{
out.writeObjectField( "stackTrace", error.getStackTraceAsString() );
}
}
finally
{
out.writeEndObject();
}
}
}
finally
{
out.writeEndArray();
currentState = State.ERRORS_WRITTEN;
}
}
catch ( IOException e )
{
loggedIOException( e );
}
}
public void transactionStatus( long expiryDate )
{
try
{
ensureDocumentOpen();
ensureResultsFieldClosed();
out.writeObjectFieldStart( "transaction" );
out.writeStringField( "expires", RFC1123.formatDate( new Date( expiryDate ) ) );
out.writeEndObject();
}
catch ( IOException e )
{
loggedIOException( e );
}
}
/**
* This method must be called exactly once, and no method must be called after calling this method.
* This method may not fail.
*/
public void finish()
{
try
{
ensureDocumentOpen();
if ( currentState != State.ERRORS_WRITTEN )
{
errors( Collections.<Neo4jError>emptyList() );
}
out.writeEndObject();
out.flush();
}
catch ( IOException e )
{
loggedIOException( e );
}
}
private ResultDataContentWriter configureWriters( ResultDataContent[] specifiers )
{
if ( specifiers == null || specifiers.length == 0 )
{
return ResultDataContent.row.writer( baseUri ); // default
}
if ( specifiers.length == 1 )
{
return specifiers[0].writer( baseUri );
}
ResultDataContentWriter[] writers = new ResultDataContentWriter[specifiers.length];
for ( int i = 0; i < specifiers.length; i++ )
{
writers[i] = specifiers[i].writer( baseUri );
}
return new AggregatingWriter( writers );
}
private enum State
{
EMPTY, DOCUMENT_OPEN, RESULTS_OPEN, RESULTS_CLOSED, ERRORS_WRITTEN
}
private State currentState = State.EMPTY;
private static final JsonFactory JSON_FACTORY = new JsonFactory( new Neo4jJsonCodec() );
private final JsonGenerator out;
private final URI baseUri;
private final StringLogger log;
private void ensureDocumentOpen() throws IOException
{
if ( currentState == State.EMPTY )
{
out.writeStartObject();
currentState = State.DOCUMENT_OPEN;
}
}
private void ensureResultsFieldOpen() throws IOException
{
ensureDocumentOpen();
if ( currentState == State.DOCUMENT_OPEN )
{
out.writeArrayFieldStart( "results" );
currentState = State.RESULTS_OPEN;
}
}
private void ensureResultsFieldClosed() throws IOException
{
ensureResultsFieldOpen();
if ( currentState == State.RESULTS_OPEN )
{
out.writeEndArray();
currentState = State.RESULTS_CLOSED;
}
}
private void writeRows( Iterable<String> columns, Iterator<Map<String, Object>> data,
ResultDataContentWriter writer ) throws IOException
{
out.writeArrayFieldStart( "data" );
try
{
while ( data.hasNext() )
{
Map<String, Object> row = data.next();
out.writeStartObject();
try
{
writer.write( out, columns, row );
}
finally
{
out.writeEndObject();
}
}
}
finally
{
out.writeEndArray(); // </data>
}
}
private void writeColumns( Iterable<String> columns ) throws IOException
{
try
{
out.writeArrayFieldStart( "columns" );
for ( String key : columns )
{
out.writeString( key );
}
}
finally
{
out.writeEndArray(); // </columns>
}
}
private IOException loggedIOException( IOException exception )
{
log.error( "Failed to generate JSON output.", exception );
return exception;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_transactional_ExecutionResultSerializer.java
|
2,648
|
public class NoAccessToDatabaseSecurityRule implements SecurityRule
{
private static boolean wasInvoked = false;
public static boolean wasInvoked()
{
return wasInvoked;
}
@Override
public boolean isAuthorized( HttpServletRequest request )
{
wasInvoked = true;
return false;
}
@Override
public String forUriPath()
{
return "/db*";
}
@Override
public String wwwAuthenticateHeader()
{
return SecurityFilter.basicAuthenticationResponse("WallyWorld");
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_security_NoAccessToDatabaseSecurityRule.java
|
2,649
|
public class AuthenticationException extends RuntimeException
{
private static final long serialVersionUID = 3662922094534872711L;
private String realm;
public AuthenticationException( String msg, String realm )
{
super( msg );
this.realm = realm;
}
public String getRealm()
{
return this.realm;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_security_AuthenticationException.java
|
2,650
|
@Provider
public class TransactionFilter extends InjectableProvider<Void> implements ResourceMethodDispatchAdapter
{
private Database database;
public TransactionFilter( Database database )
{
super( Void.class );
this.database = database;
}
@Override
public Void getValue( HttpContext httpContext )
{
throw new IllegalStateException( "This _really_ should never happen" );
}
@Override
public ResourceMethodDispatchProvider adapt( final ResourceMethodDispatchProvider resourceMethodDispatchProvider )
{
return new ResourceMethodDispatchProvider()
{
@Override
public RequestDispatcher create( AbstractResourceMethod abstractResourceMethod )
{
final RequestDispatcher requestDispatcher = resourceMethodDispatchProvider.create(
abstractResourceMethod );
return new TransactionalRequestDispatcher( database, requestDispatcher );
}
};
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_transactional_TransactionFilter.java
|
2,651
|
{
@Override
protected void serialize( MappingSerializer serializer )
{
ArrayList<Representation> maps = new ArrayList<Representation>();
maps.add( new MappingRepresentation( "map" )
{
@Override
protected void serialize( MappingSerializer serializer )
{
serializer.putString( "foo", "bar" );
}
} );
serializer.putList( "foo", new ServerListRepresentation( RepresentationType.MAP, maps ) );
}
} );
| false
|
community_server_src_test_java_org_neo4j_server_rest_repr_formats_JsonFormatTest.java
|
2,652
|
{
@Override
protected void serialize( MappingSerializer serializer )
{
serializer.putMapping( "nested", new MappingRepresentation( "data" )
{
@Override
protected void serialize( MappingSerializer nested )
{
nested.putString( "data", "expected data" );
}
} );
}
} );
| false
|
community_server_src_test_java_org_neo4j_server_rest_repr_formats_JsonFormatTest.java
|
2,653
|
{
@Override
protected void serialize( MappingSerializer serializer )
{
serializer.putUri( "URL", "subpath" );
}
} );
| false
|
community_server_src_test_java_org_neo4j_server_rest_repr_formats_JsonFormatTest.java
|
2,654
|
{
@Override
protected void serialize( MappingSerializer serializer )
{
serializer.putString( "key", "expected string" );
}
} );
| false
|
community_server_src_test_java_org_neo4j_server_rest_repr_formats_JsonFormatTest.java
|
2,655
|
{
@Override
protected void serialize( MappingSerializer serializer )
{
}
} );
| false
|
community_server_src_test_java_org_neo4j_server_rest_repr_formats_JsonFormatTest.java
|
2,656
|
public class JsonFormatTest
{
private OutputFormat json;
@Before
public void createOutputFormat() throws Exception
{
json = new OutputFormat( new JsonFormat(), new URI( "http://localhost/" ), null );
}
@Test
public void canFormatString() throws Exception
{
String entity = json.assemble( ValueRepresentation.string( "expected value" ) );
assertEquals( entity, "\"expected value\"" );
}
@Test
public void canFormatListOfStrings() throws Exception
{
String entity = json.assemble( ListRepresentation.strings( "hello", "world" ) );
String expectedString = JsonHelper.createJsonFrom( Arrays.asList( "hello", "world" ) );
assertEquals( expectedString, entity );
}
@Test
public void canFormatInteger() throws Exception
{
String entity = json.assemble( ValueRepresentation.number( 10 ) );
assertEquals( "10", entity );
}
@Test
public void canFormatEmptyObject() throws Exception
{
String entity = json.assemble( new MappingRepresentation( "empty" )
{
@Override
protected void serialize( MappingSerializer serializer )
{
}
} );
assertEquals( JsonHelper.createJsonFrom( Collections.emptyMap() ), entity );
}
@Test
public void canFormatObjectWithStringField() throws Exception
{
String entity = json.assemble( new MappingRepresentation( "string" )
{
@Override
protected void serialize( MappingSerializer serializer )
{
serializer.putString( "key", "expected string" );
}
} );
assertEquals( JsonHelper.createJsonFrom( Collections.singletonMap( "key", "expected string" ) ), entity );
}
@Test
public void canFormatObjectWithUriField() throws Exception
{
String entity = json.assemble( new MappingRepresentation( "uri" )
{
@Override
protected void serialize( MappingSerializer serializer )
{
serializer.putUri( "URL", "subpath" );
}
} );
assertEquals( JsonHelper.createJsonFrom( Collections.singletonMap( "URL", "http://localhost/subpath" ) ),
entity );
}
@Test
public void canFormatObjectWithNestedObject() throws Exception
{
String entity = json.assemble( new MappingRepresentation( "nesting" )
{
@Override
protected void serialize( MappingSerializer serializer )
{
serializer.putMapping( "nested", new MappingRepresentation( "data" )
{
@Override
protected void serialize( MappingSerializer nested )
{
nested.putString( "data", "expected data" );
}
} );
}
} );
assertEquals(
JsonHelper.createJsonFrom( Collections.singletonMap( "nested",
Collections.singletonMap( "data", "expected data" ) ) ), entity );
}
@Test
public void canFormatNestedMapsAndLists() throws Exception
{
String entity = json.assemble( new MappingRepresentation( "test" )
{
@Override
protected void serialize( MappingSerializer serializer )
{
ArrayList<Representation> maps = new ArrayList<Representation>();
maps.add( new MappingRepresentation( "map" )
{
@Override
protected void serialize( MappingSerializer serializer )
{
serializer.putString( "foo", "bar" );
}
} );
serializer.putList( "foo", new ServerListRepresentation( RepresentationType.MAP, maps ) );
}
} );
assertEquals( "bar",((Map)((List)((Map)JsonHelper.jsonToMap(entity)).get("foo")).get(0)).get("foo") );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_repr_formats_JsonFormatTest.java
|
2,657
|
public class JsonFormat extends RepresentationFormat
{
public JsonFormat()
{
super( MediaType.APPLICATION_JSON_TYPE );
}
@Override
protected ListWriter serializeList( String type )
{
return new ListWrappingWriter( new ArrayList<Object>() );
}
@Override
protected String complete( ListWriter serializer )
{
return JsonHelper.createJsonFrom( ( (ListWrappingWriter) serializer ).data );
}
@Override
protected MappingWriter serializeMapping( String type )
{
return new MapWrappingWriter( new LinkedHashMap<String, Object>() );
}
@Override
protected String complete( MappingWriter serializer )
{
return JsonHelper.createJsonFrom( ( (MapWrappingWriter) serializer ).data );
}
@Override
protected String serializeValue( String type, Object value )
{
return JsonHelper.createJsonFrom( value );
}
private boolean empty( String input )
{
return input == null || "".equals( input.trim() );
}
@Override
public Map<String, Object> readMap( String input, String... requiredKeys ) throws BadInputException
{
if ( empty( input ) ) return DefaultFormat.validateKeys( Collections.<String,Object>emptyMap(), requiredKeys );
try
{
return DefaultFormat.validateKeys( JsonHelper.jsonToMap( stripByteOrderMark( input ) ), requiredKeys );
}
catch ( Exception ex )
{
throw new BadInputException( ex );
}
}
@Override
@SuppressWarnings( "unchecked" )
public List<Object> readList( String input ) throws BadInputException
{
try
{
return (List<Object>) JsonHelper.readJson( input );
}
catch ( ClassCastException ex )
{
throw new BadInputException( ex );
}
catch ( JsonParseException ex )
{
throw new BadInputException( ex );
}
}
@Override
public Object readValue( String input ) throws BadInputException
{
if ( empty( input ) ) return Collections.emptyMap();
try
{
return JsonHelper.jsonToSingleValue( stripByteOrderMark( input ) );
}
catch ( JsonParseException ex )
{
throw new BadInputException( ex );
}
}
@Override
public URI readUri( String input ) throws BadInputException
{
try
{
return new URI( readValue( input ).toString() );
}
catch ( URISyntaxException e )
{
throw new BadInputException( e );
}
}
private String stripByteOrderMark( String string )
{
if ( string != null && string.length() > 0 && string.charAt( 0 ) == 0xfeff )
{
return string.substring( 1 );
}
return string;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_formats_JsonFormat.java
|
2,658
|
EXCEPTION( Representation.EXCEPTION )
{
@Override
String render( Map<String, Object> serialized )
{
StringBuilder entity = new StringBuilder( "<html>" );
entity.append( "<head><title>Error</title></head><body>" );
Object subjectOrNull = serialized.get( "message" );
if ( subjectOrNull != null )
{
entity.append( "<p><pre>" )
.append( subjectOrNull )
.append( "</pre></p>" );
}
entity.append( "<p><pre>" )
.append( serialized.get( "exception" ) );
List<Object> tb = (List<Object>) serialized.get( "stacktrace" );
if ( tb != null )
{
for ( Object el : tb )
entity.append( "\n\tat " + el );
}
entity.append( "</pre></p>" )
.append( "</body></html>" );
return entity.toString();
}
};
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_formats_HtmlFormat.java
|
2,659
|
GRAPHDB( Representation.GRAPHDB )
{
@Override
String render( Map<String, Object> serialized )
{
Map<Object, Object> map = new HashMap<>();
transfer( serialized, map, "index", "node_index", "relationship_index"/*, "extensions_info"*/);
return HtmlHelper.from( map, HtmlHelper.ObjectType.ROOT );
}
},
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_formats_HtmlFormat.java
|
2,660
|
RELATIONSHIP_INDEXES( Representation.RELATIONSHIP_INDEXES )
{
@Override
String render( Map<String, Object> serialized )
{
return renderIndex( serialized );
}
},
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_formats_HtmlFormat.java
|
2,661
|
NODE_INDEXES( Representation.NODE_INDEXES )
{
@Override
String render( Map<String, Object> serialized )
{
return renderIndex( serialized );
}
},
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_formats_HtmlFormat.java
|
2,662
|
RELATIONSHIP( Representation.RELATIONSHIP )
{
@Override
String render( Map<String, Object> serialized )
{
Map<Object, Object> map = new LinkedHashMap<Object, Object>();
transfer( serialized, map, "type", "data", "start", "end" );
return HtmlHelper.from( map, HtmlHelper.ObjectType.RELATIONSHIP );
}
},
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_formats_HtmlFormat.java
|
2,663
|
NODE( Representation.NODE )
{
@Override
String render( Map<String, Object> serialized )
{
String javascript = "";
StringBuilder builder = HtmlHelper.start( HtmlHelper.ObjectType.NODE, javascript );
HtmlHelper.append( builder, Collections.singletonMap( "data", serialized.get( "data" ) ),
HtmlHelper.ObjectType.NODE );
builder.append( "<form action='javascript:neo4jHtmlBrowse.getRelationships();'><fieldset><legend>Get relationships</legend>\n" );
builder.append( "<label for='direction'>with direction</label>\n" + "<select id='direction'>" );
builder.append( "<option value='" )
.append( serialized.get( "all_typed_relationships" ) )
.append( "'>all</option>" );
builder.append( "<option value='" )
.append( serialized.get( "incoming_typed_relationships" ) )
.append( "'>in</option>" );
builder.append( "<option value='" )
.append( serialized.get( "outgoing_typed_relationships" ) )
.append( "'>out</option>" );
builder.append( "</select>\n" );
builder.append( "<label for='types'>for type(s)</label><select id='types' multiple='multiple'>" );
for ( String relationshipType : (List<String>) serialized.get( "relationship_types" ) )
{
builder.append( "<option selected='selected' value='" )
.append( relationshipType )
.append( "'>" );
builder.append( relationshipType )
.append( "</option>" );
}
builder.append( "</select>\n" );
builder.append( "<button>Get</button>\n" );
builder.append( "</fieldset></form>\n" );
return HtmlHelper.end( builder );
}
},
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_formats_HtmlFormat.java
|
2,664
|
RELATIONSHIPS
{
@Override
String render( List<Object> data )
{
if ( data.isEmpty() )
{
StringBuilder builder = HtmlHelper.start( HtmlHelper.ObjectType.RELATIONSHIP, null );
HtmlHelper.appendMessage( builder, "No relationships found" );
return HtmlHelper.end( builder );
}
else
{
Collection<Object> list = new ArrayList<Object>();
for ( Map<?, ?> serialized : (List<Map<?, ?>>) (List<?>) data )
{
Map<Object, Object> map = new LinkedHashMap<Object, Object>();
transfer( serialized, map, "self", "type", "data", "start", "end" );
list.add( map );
}
return HtmlHelper.from( list, HtmlHelper.ObjectType.RELATIONSHIP );
}
}
};
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_formats_HtmlFormat.java
|
2,665
|
NODES
{
@Override
String render( List<Object> data )
{
StringBuilder builder = HtmlHelper.start( "Index hits", null );
if ( data.isEmpty() )
{
HtmlHelper.appendMessage( builder, "No index hits" );
return HtmlHelper.end( builder );
}
else
{
for ( Map<?, ?> serialized : (List<Map<?, ?>>) (List<?>) data )
{
Map<Object, Object> map = new LinkedHashMap<Object, Object>();
transfer( serialized, map, "self", "data" );
HtmlHelper.append( builder, map, HtmlHelper.ObjectType.NODE );
}
return HtmlHelper.end( builder );
}
}
},
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_formats_HtmlFormat.java
|
2,666
|
private static class HtmlMap extends MapWrappingWriter
{
private final MappingTemplate template;
public HtmlMap( MappingTemplate template )
{
super( new HashMap<String, Object>(), true );
this.template = template;
}
String complete()
{
return template.render( this.data );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_formats_HtmlFormat.java
|
2,667
|
private static class HtmlList extends ListWrappingWriter
{
private final ListTemplate template;
public HtmlList( ListTemplate template )
{
super( new ArrayList<Object>(), true );
this.template = template;
}
String complete()
{
return template.render( this.data );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_formats_HtmlFormat.java
|
2,668
|
public class HtmlFormat extends RepresentationFormat
{
public HtmlFormat()
{
super( MediaType.TEXT_HTML_TYPE );
}
private enum MappingTemplate
{
NODE( Representation.NODE )
{
@Override
String render( Map<String, Object> serialized )
{
String javascript = "";
StringBuilder builder = HtmlHelper.start( HtmlHelper.ObjectType.NODE, javascript );
HtmlHelper.append( builder, Collections.singletonMap( "data", serialized.get( "data" ) ),
HtmlHelper.ObjectType.NODE );
builder.append( "<form action='javascript:neo4jHtmlBrowse.getRelationships();'><fieldset><legend>Get relationships</legend>\n" );
builder.append( "<label for='direction'>with direction</label>\n" + "<select id='direction'>" );
builder.append( "<option value='" )
.append( serialized.get( "all_typed_relationships" ) )
.append( "'>all</option>" );
builder.append( "<option value='" )
.append( serialized.get( "incoming_typed_relationships" ) )
.append( "'>in</option>" );
builder.append( "<option value='" )
.append( serialized.get( "outgoing_typed_relationships" ) )
.append( "'>out</option>" );
builder.append( "</select>\n" );
builder.append( "<label for='types'>for type(s)</label><select id='types' multiple='multiple'>" );
for ( String relationshipType : (List<String>) serialized.get( "relationship_types" ) )
{
builder.append( "<option selected='selected' value='" )
.append( relationshipType )
.append( "'>" );
builder.append( relationshipType )
.append( "</option>" );
}
builder.append( "</select>\n" );
builder.append( "<button>Get</button>\n" );
builder.append( "</fieldset></form>\n" );
return HtmlHelper.end( builder );
}
},
RELATIONSHIP( Representation.RELATIONSHIP )
{
@Override
String render( Map<String, Object> serialized )
{
Map<Object, Object> map = new LinkedHashMap<Object, Object>();
transfer( serialized, map, "type", "data", "start", "end" );
return HtmlHelper.from( map, HtmlHelper.ObjectType.RELATIONSHIP );
}
},
NODE_INDEXES( Representation.NODE_INDEXES )
{
@Override
String render( Map<String, Object> serialized )
{
return renderIndex( serialized );
}
},
RELATIONSHIP_INDEXES( Representation.RELATIONSHIP_INDEXES )
{
@Override
String render( Map<String, Object> serialized )
{
return renderIndex( serialized );
}
},
GRAPHDB( Representation.GRAPHDB )
{
@Override
String render( Map<String, Object> serialized )
{
Map<Object, Object> map = new HashMap<>();
transfer( serialized, map, "index", "node_index", "relationship_index"/*, "extensions_info"*/);
return HtmlHelper.from( map, HtmlHelper.ObjectType.ROOT );
}
},
EXCEPTION( Representation.EXCEPTION )
{
@Override
String render( Map<String, Object> serialized )
{
StringBuilder entity = new StringBuilder( "<html>" );
entity.append( "<head><title>Error</title></head><body>" );
Object subjectOrNull = serialized.get( "message" );
if ( subjectOrNull != null )
{
entity.append( "<p><pre>" )
.append( subjectOrNull )
.append( "</pre></p>" );
}
entity.append( "<p><pre>" )
.append( serialized.get( "exception" ) );
List<Object> tb = (List<Object>) serialized.get( "stacktrace" );
if ( tb != null )
{
for ( Object el : tb )
entity.append( "\n\tat " + el );
}
entity.append( "</pre></p>" )
.append( "</body></html>" );
return entity.toString();
}
};
private final String key;
private MappingTemplate( String key )
{
this.key = key;
}
static final Map<String, MappingTemplate> TEMPLATES = new HashMap<String, MappingTemplate>();
static
{
for ( MappingTemplate template : values() )
TEMPLATES.put( template.key, template );
}
abstract String render( Map<String, Object> data );
}
private enum ListTemplate
{
NODES
{
@Override
String render( List<Object> data )
{
StringBuilder builder = HtmlHelper.start( "Index hits", null );
if ( data.isEmpty() )
{
HtmlHelper.appendMessage( builder, "No index hits" );
return HtmlHelper.end( builder );
}
else
{
for ( Map<?, ?> serialized : (List<Map<?, ?>>) (List<?>) data )
{
Map<Object, Object> map = new LinkedHashMap<Object, Object>();
transfer( serialized, map, "self", "data" );
HtmlHelper.append( builder, map, HtmlHelper.ObjectType.NODE );
}
return HtmlHelper.end( builder );
}
}
},
RELATIONSHIPS
{
@Override
String render( List<Object> data )
{
if ( data.isEmpty() )
{
StringBuilder builder = HtmlHelper.start( HtmlHelper.ObjectType.RELATIONSHIP, null );
HtmlHelper.appendMessage( builder, "No relationships found" );
return HtmlHelper.end( builder );
}
else
{
Collection<Object> list = new ArrayList<Object>();
for ( Map<?, ?> serialized : (List<Map<?, ?>>) (List<?>) data )
{
Map<Object, Object> map = new LinkedHashMap<Object, Object>();
transfer( serialized, map, "self", "type", "data", "start", "end" );
list.add( map );
}
return HtmlHelper.from( list, HtmlHelper.ObjectType.RELATIONSHIP );
}
}
};
abstract String render( List<Object> data );
}
private static void transfer( Map<?, ?> from, Map<Object, Object> to, String... keys )
{
for ( String key : keys )
{
Object value = from.get( key );
if ( value != null )
{
to.put( key, value );
}
}
}
private static String renderIndex( Map<String, Object> serialized )
{
String javascript = "";
StringBuilder builder = HtmlHelper.start( HtmlHelper.ObjectType.INDEX_ROOT, javascript );
int counter = 0;
for ( String indexName : serialized.keySet() )
{
Map<?, ?> indexMapObject = (Map<?, ?>) serialized.get( indexName );
builder.append( "<ul>" );
{
builder.append( "<li>" );
Map<?, ?> indexMap = indexMapObject;
String keyId = "key_" + counter;
String valueId = "value_" + counter;
builder.append( "<form action='javascript:neo4jHtmlBrowse.search(\"" )
.append( indexMap.get( "template" ) )
.append( "\",\"" )
.append( keyId )
.append( "\",\"" )
.append( valueId )
.append( "\");'><fieldset><legend> name: " )
.append( indexName )
.append( " (configuration: " )
.append( indexMap.get( "type" ) )
.append( ")</legend>\n" );
builder.append( "<label for='" )
.append( keyId )
.append( "'>Key</label><input id='" )
.append( keyId )
.append( "'>\n" );
builder.append( "<label for='" )
.append( valueId )
.append( "'>Value</label><input id='" )
.append( valueId )
.append( "'>\n" );
builder.append( "<button>Search</button>\n" );
builder.append( "</fieldset></form>\n" );
builder.append( "</li>\n" );
counter++;
}
builder.append( "</ul>" );
}
return HtmlHelper.end( builder );
}
private static class HtmlMap extends MapWrappingWriter
{
private final MappingTemplate template;
public HtmlMap( MappingTemplate template )
{
super( new HashMap<String, Object>(), true );
this.template = template;
}
String complete()
{
return template.render( this.data );
}
}
private static class HtmlList extends ListWrappingWriter
{
private final ListTemplate template;
public HtmlList( ListTemplate template )
{
super( new ArrayList<Object>(), true );
this.template = template;
}
String complete()
{
return template.render( this.data );
}
}
@Override
protected String complete( ListWriter serializer )
{
return ( (HtmlList) serializer ).complete();
}
@Override
protected String complete( MappingWriter serializer )
{
return ( (HtmlMap) serializer ).complete();
}
@Override
protected ListWriter serializeList( String type )
{
if ( Representation.NODE_LIST.equals( type ) )
{
return new HtmlList( ListTemplate.NODES );
}
else if ( Representation.RELATIONSHIP_LIST.equals( type ) )
{
return new HtmlList( ListTemplate.RELATIONSHIPS );
}
else
{
throw new WebApplicationException( Response.status( Response.Status.NOT_ACCEPTABLE )
.entity( "Cannot represent \"" + type + "\" as html" )
.build() );
}
}
@Override
protected MappingWriter serializeMapping( String type )
{
MappingTemplate template = MappingTemplate.TEMPLATES.get( type );
if ( template == null )
{
throw new WebApplicationException( Response.status( Response.Status.NOT_ACCEPTABLE )
.entity( "Cannot represent \"" + type + "\" as html" )
.build() );
}
return new HtmlMap( template );
}
@Override
protected String serializeValue( String type, Object value )
{
throw new WebApplicationException( Response.status( Response.Status.NOT_ACCEPTABLE )
.entity( "Cannot represent \"" + type + "\" as html" )
.build() );
}
@Override
public List<Object> readList( String input ) throws BadInputException
{
throw new WebApplicationException( Response.status( Response.Status.UNSUPPORTED_MEDIA_TYPE )
.entity( "Cannot read html" )
.build() );
}
@Override
public Map<String, Object> readMap( String input, String... requiredKeys ) throws BadInputException
{
throw new WebApplicationException( Response.status( Response.Status.UNSUPPORTED_MEDIA_TYPE )
.entity( "Cannot read html" )
.build() );
}
@Override
public URI readUri( String input ) throws BadInputException
{
throw new WebApplicationException( Response.status( Response.Status.UNSUPPORTED_MEDIA_TYPE )
.entity( "Cannot read html" )
.build() );
}
@Override
public Object readValue( String input ) throws BadInputException
{
throw new WebApplicationException( Response.status( Response.Status.UNSUPPORTED_MEDIA_TYPE )
.entity( "Cannot read html" )
.build() );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_formats_HtmlFormat.java
|
2,669
|
public class DefaultFormatTest
{
private DefaultFormat input;
@Before
public void setUp() throws Exception
{
JsonFormat inner = new JsonFormat();
ArrayList<MediaType> supported = new ArrayList<MediaType>();
MediaType requested = MediaType.APPLICATION_JSON_TYPE;
input = new DefaultFormat( inner, supported, requested );
}
@Test
public void canReadEmptyMap() throws Exception
{
Map<String, Object> map = input.readMap( "{}" );
assertNotNull( map );
assertTrue( "map is not empty", map.isEmpty() );
}
@Test
public void canReadMapWithTwoValues() throws Exception
{
Map<String, Object> map = input.readMap( "{\"key1\":\"value1\", \"key2\":\"value11\"}" );
assertNotNull( map );
assertThat( map, hasEntry( "key1", (Object) "value1" ) );
assertThat( map, hasEntry( "key2", (Object) "value11" ) );
assertTrue( "map contained extra values", map.size() == 2 );
}
@Test
public void canReadMapWithNestedMap() throws Exception
{
Map<String, Object> map = input.readMap( "{\"nested\": {\"key\": \"valuable\"}}" );
assertNotNull( map );
assertThat( map, hasKey( "nested" ) );
assertTrue( "map contained extra values", map.size() == 1 );
Object nested = map.get( "nested" );
assertThat( nested, instanceOf( Map.class ) );
@SuppressWarnings( "unchecked" ) Map<String, String> nestedMap = (Map<String, String>) nested;
assertThat( nestedMap, hasEntry( "key", "valuable" ) );
}
@Test( expected = MediaTypeNotSupportedException.class )
public void failsWithTheCorrectExceptionWhenGettingTheWrongInput() throws BadInputException
{
input.readValue( "<xml />" );
}
@Test( expected = MediaTypeNotSupportedException.class )
public void failsWithTheCorrectExceptionWhenGettingTheWrongInput2() throws BadInputException
{
input.readMap( "<xml />" );
}
@Test( expected = MediaTypeNotSupportedException.class )
public void failsWithTheCorrectExceptionWhenGettingTheWrongInput3() throws BadInputException
{
input.readUri( "<xml />" );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_repr_formats_DefaultFormatTest.java
|
2,670
|
{
@Override
protected void serialize( MappingSerializer serializer )
{
serializer.putString( "key", "expected string" );
}
} );
| false
|
community_server_src_test_java_org_neo4j_server_rest_repr_formats_CompactJsonFormatTest.java
|
2,671
|
{
@Override
protected void serialize( MappingSerializer nested )
{
nested.putString( "data", "expected data" );
}
} );
| false
|
community_server_src_test_java_org_neo4j_server_rest_repr_formats_JsonFormatTest.java
|
2,672
|
{
@Override
protected void serialize( MappingSerializer serializer )
{
serializer.putString( "foo", "bar" );
}
} );
| false
|
community_server_src_test_java_org_neo4j_server_rest_repr_formats_JsonFormatTest.java
|
2,673
|
public class RFC1123Test
{
private final Calendar calendar = Calendar.getInstance( RFC1123.GMT, Locale.US );
@Test
public void shouldParseRFC1123() throws Exception
{
// given
String input = "Mon, 15 Aug 2005 15:52:01 +0000";
// when
Date result = RFC1123.parseTimestamp( input );
// then
calendar.setTime( result );
assertEquals( Calendar.MONDAY, calendar.get( Calendar.DAY_OF_WEEK ) );
assertEquals( 15, calendar.get( Calendar.DAY_OF_MONTH ) );
assertEquals( Calendar.AUGUST, calendar.get( Calendar.MONTH ) );
assertEquals( 2005, calendar.get( Calendar.YEAR ) );
assertEquals( 15, calendar.get( Calendar.HOUR_OF_DAY ) );
assertEquals( 52, calendar.get( Calendar.MINUTE ) );
assertEquals( 1, calendar.get( Calendar.SECOND ) );
}
@Test
public void shouldFormatRFC1123() throws Exception
{
// given
String input = "Mon, 15 Aug 2005 15:52:01 +0000";
// when
String output = RFC1123.formatDate( RFC1123.parseTimestamp( input ) );
// then
assertEquals( input, output );
}
@Test
public void shouldReturnSameInstanceInSameThread() throws Exception
{
// given
RFC1123 instance = RFC1123.instance();
// when
RFC1123 instance2 = RFC1123.instance();
// then
assertTrue(
"Expected to get same instance from second call to RFC1123.instance() in same thread",
instance == instance2 );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_repr_util_RFC1123Test.java
|
2,674
|
public class JsonInputTest
{
private final JsonFormat input = new JsonFormat();
@Test
public void canReadEmptyMap() throws Exception
{
Map<String, Object> map = input.readMap( "{}" );
assertNotNull( map );
assertTrue( "map is not empty", map.isEmpty() );
}
@Test
public void canReadMapWithTwoValues() throws Exception
{
Map<String, Object> map = input.readMap( "{\"key1\":\"value1\", \"key2\":\"value11\"}" );
assertNotNull( map );
assertThat( map, hasEntry( "key1", (Object) "value1" ) );
assertThat( map, hasEntry( "key2", (Object) "value11" ) );
assertTrue( "map contained extra values", map.size() == 2 );
}
@Test
public void canReadMapWithNestedMap() throws Exception
{
Map<String, Object> map = input.readMap( "{\"nested\": {\"key\": \"valuable\"}}" );
assertNotNull( map );
assertThat( map, hasKey( "nested" ) );
assertTrue( "map contained extra values", map.size() == 1 );
Object nested = map.get( "nested" );
assertThat( nested, instanceOf( Map.class ) );
@SuppressWarnings( "unchecked" ) Map<String, String> nestedMap = (Map<String, String>) nested;
assertThat( nestedMap, hasEntry( "key", "valuable" ) );
}
@Test
public void canReadStringWithLineBreaks() throws Exception
{
Map<String, Object> map = input.readMap( "{\"key\": \"v1\\nv2\"}" );
assertNotNull( map );
assertEquals( map.get( "key" ), "v1\nv2" );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_repr_formats_JsonInputTest.java
|
2,675
|
public final class RFC1123
{
private static final ThreadLocal<RFC1123> INSTANCES = new ThreadLocal<RFC1123>();
public static final TimeZone GMT = TimeZone.getTimeZone( "GMT" );
private static final Date Y2K_START_DATE;
static {
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone( GMT );
calendar.set( 2000, Calendar.JANUARY, 1, 0, 0, 0 );
calendar.set( Calendar.MILLISECOND, 0 );
Y2K_START_DATE = calendar.getTime();
}
private final SimpleDateFormat format;
private RFC1123()
{
format = new SimpleDateFormat( "EEE, dd MMM yyyy HH:mm:ss Z", Locale.US );
format.setTimeZone( GMT );
}
public Date parse(String input) throws ParseException
{
format.set2DigitYearStart( Y2K_START_DATE );
return format.parse( input );
}
public String format(Date date)
{
if ( null == date )
throw new IllegalArgumentException( "Date is null" );
return format.format( date );
}
static final RFC1123 instance()
{
RFC1123 instance = INSTANCES.get();
if ( null == instance )
{
instance = new RFC1123();
INSTANCES.set( instance );
}
return instance;
}
public static Date parseTimestamp(String input) throws ParseException
{
return instance().parse( input );
}
public static String formatDate(Date date)
{
return instance().format( date );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_util_RFC1123.java
|
2,676
|
public class UrlFormFormatTest
{
@Test
public void shouldParseEmptyMap() throws Exception
{
UrlFormFormat format = new UrlFormFormat();
Map<String, Object> map = format.readMap( "" );
assertThat( map.size(), is( 0 ) );
}
@Test
public void canParseSingleKeyMap() throws Exception
{
UrlFormFormat format = new UrlFormFormat();
Map<String, Object> map = format.readMap( "var=A" );
assertThat( map.size(), is( 1 ) );
assertThat( (String) map.get( "var" ), is( "A" ) );
}
@Test
public void canParseListsInMaps() throws Exception
{
UrlFormFormat format = new UrlFormFormat();
Map<String, Object> map = format.readMap( "var=A&var=B" );
assertThat( map.size(), is( 1 ) );
assertThat( ( (List<String>) map.get( "var" ) ).get( 0 ), is( "A" ) );
assertThat( ( (List<String>) map.get( "var" ) ).get( 1 ), is( "B" ) );
}
@Test
public void shouldSupportPhpStyleUrlEncodedPostBodiesForAListOnly() throws Exception
{
UrlFormFormat format = new UrlFormFormat();
Map<String, Object> map = format.readMap( "var[]=A&var[]=B" );
assertThat( map.size(), is( 1 ) );
assertThat( ( (List<String>) map.get( "var" ) ).get( 0 ), is( "A" ) );
assertThat( ( (List<String>) map.get( "var" ) ).get( 1 ), is( "B" ) );
}
@Test
public void shouldSupportPhpStyleUrlEncodedPostBodiesForAListAndNonListParams() throws Exception
{
UrlFormFormat format = new UrlFormFormat();
Map<String, Object> map = format.readMap( "var[]=A&var[]=B&foo=bar" );
assertThat( map.size(), is( 2 ) );
assertThat( ( (List<String>) map.get( "var" ) ).get( 0 ), is( "A" ) );
assertThat( ( (List<String>) map.get( "var" ) ).get( 1 ), is( "B" ) );
assertEquals( "bar", map.get( "foo" ) );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_repr_formats_UrlFormFormatTest.java
|
2,677
|
public class UrlFormFormat extends RepresentationFormat
{
public UrlFormFormat()
{
super( MediaType.APPLICATION_FORM_URLENCODED_TYPE );
}
@Override
protected String serializeValue( final String type, final Object value )
{
throw new RuntimeException( "Not implemented!" );
}
@Override
protected ListWriter serializeList( final String type )
{
throw new RuntimeException( "Not implemented!" );
}
@Override
protected MappingWriter serializeMapping( final String type )
{
throw new RuntimeException( "Not implemented!" );
}
@Override
protected String complete( final ListWriter serializer )
{
throw new RuntimeException( "Not implemented!" );
}
@Override
protected String complete( final MappingWriter serializer )
{
throw new RuntimeException( "Not implemented!" );
}
@Override
public Object readValue( final String input ) throws BadInputException
{
throw new RuntimeException( "Not implemented!" );
}
@Override
public Map<String, Object> readMap( final String input, String... requiredKeys ) throws BadInputException
{
HashMap<String, Object> result = new HashMap<String, Object>();
if ( input.isEmpty() )
{
return result;
}
for ( String pair : input.split( "\\&" ) )
{
String[] fields = pair.split( "=" );
String key;
String value;
try
{
key = ensureThatKeyDoesNotHavePhPStyleParenthesesAtTheEnd( URLDecoder.decode( fields[0], "UTF-8" ) );
value = URLDecoder.decode( fields[1], "UTF-8" );
}
catch ( UnsupportedEncodingException e )
{
throw new BadInputException( e );
}
Object old = result.get( key );
if ( old == null )
{
result.put( key, value );
}
else
{
List<Object> list;
if ( old instanceof List<?> )
{
list = (List<Object>) old;
}
else
{
list = new ArrayList<Object>();
result.put( key, list );
list.add( old );
}
list.add( value );
}
}
return DefaultFormat.validateKeys( result, requiredKeys );
}
private String ensureThatKeyDoesNotHavePhPStyleParenthesesAtTheEnd( String key )
{
if ( key.endsWith( "[]" ) )
{
return key.substring( 0, key.length() - 2 );
}
return key;
}
@Override
public List<Object> readList( final String input ) throws BadInputException
{
throw new RuntimeException( "Not implemented!" );
}
@Override
public URI readUri( final String input ) throws BadInputException
{
throw new RuntimeException( "Not implemented!" );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_formats_UrlFormFormat.java
|
2,678
|
public class StreamingJsonUtils {
public static String readCurrentValueAsString(JsonParser jp, JsonToken token) throws JsonParseException, IOException {
return readCurrentValueInto(jp, token, new StringBuilder()).toString();
}
private static StringBuilder readCurrentValueInto(JsonParser jp, JsonToken token, StringBuilder b) throws JsonParseException, IOException {
if( token == JsonToken.START_OBJECT ) {
boolean first = true;
b.append('{');
while( (token = jp.nextToken()) != JsonToken.END_OBJECT && token != null) {
if(!first)
b.append(',');
else
first = false;
b.append('"');
b.append(jp.getText());
b.append('"');
b.append(':');
readCurrentValueInto(jp, jp.nextToken(), b);
}
b.append('}');
} else if( token == JsonToken.START_ARRAY ) {
boolean first = true;
b.append('[');
while( (token = jp.nextToken()) != JsonToken.END_ARRAY && token != null) {
if(!first)
b.append(',');
else
first = false;
readCurrentValueInto(jp, token, b);
}
b.append(']');
} else if ( token == JsonToken.VALUE_STRING ) {
b.append('"');
b.append(jp.getText());
b.append('"');
} else if ( token == JsonToken.VALUE_FALSE ) {
b.append("false");
} else if ( token == JsonToken.VALUE_TRUE ) {
b.append("true");
} else if ( token == JsonToken.VALUE_NULL ) {
b.append("null");
} else {
b.append(jp.getText());
}
return b;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_formats_StreamingJsonUtils.java
|
2,679
|
{
@Override
protected void serialize( MappingSerializer nested )
{
nested.putString( "data", "expected data" );
}
} );
| false
|
community_server_src_test_java_org_neo4j_server_rest_repr_formats_StreamingJsonFormatTest.java
|
2,680
|
{
@Override
protected void serialize( MappingSerializer serializer )
{
serializer.putMapping( "nested", new MappingRepresentation( "data" )
{
@Override
protected void serialize( MappingSerializer nested )
{
nested.putString( "data", "expected data" );
}
} );
}
} );
| false
|
community_server_src_test_java_org_neo4j_server_rest_repr_formats_StreamingJsonFormatTest.java
|
2,681
|
{
@Override
protected void serialize( MappingSerializer serializer )
{
serializer.putUri( "URL", "subpath" );
}
} );
| false
|
community_server_src_test_java_org_neo4j_server_rest_repr_formats_StreamingJsonFormatTest.java
|
2,682
|
{
@Override
protected void serialize( MappingSerializer serializer )
{
serializer.putString( "key", "expected string" );
}
} );
| false
|
community_server_src_test_java_org_neo4j_server_rest_repr_formats_StreamingJsonFormatTest.java
|
2,683
|
{
@Override
protected void serialize( MappingSerializer serializer )
{
}
} );
| false
|
community_server_src_test_java_org_neo4j_server_rest_repr_formats_StreamingJsonFormatTest.java
|
2,684
|
public class StreamingJsonFormatTest
{
private OutputFormat json;
private ByteArrayOutputStream stream;
@Before
public void createOutputFormat() throws Exception
{
stream = new ByteArrayOutputStream();
json = new OutputFormat( new StreamingJsonFormat().writeTo(stream).usePrettyPrinter(), new URI( "http://localhost/" ), null );
}
@Test
public void canFormatNode() throws Exception
{
GraphDatabaseService db = new TestGraphDatabaseFactory().newImpermanentDatabase();
Transaction transaction = db.beginTx();
try
{
final Node n = db.createNode();
json.assemble( new NodeRepresentation( n ) );
}
finally
{
transaction.finish();
db.shutdown();
}
assertTrue( stream.toString().contains( "\"self\" : \"http://localhost/node/0\"," ) );
}
@Test
public void canFormatString() throws Exception
{
json.assemble( ValueRepresentation.string( "expected value" ) );
assertEquals( stream.toString(), "\"expected value\"" );
}
@Test
public void canFormatListOfStrings() throws Exception
{
json.assemble( ListRepresentation.strings( "hello", "world" ) );
String expectedString = JsonHelper.createJsonFrom( Arrays.asList( "hello", "world" ) );
assertEquals( expectedString, stream.toString() );
}
@Test
public void canFormatInteger() throws Exception
{
json.assemble( ValueRepresentation.number( 10 ) );
assertEquals( "10", stream.toString() );
}
@Test
public void canFormatEmptyObject() throws Exception
{
json.assemble( new MappingRepresentation( "empty" )
{
@Override
protected void serialize( MappingSerializer serializer )
{
}
} );
assertEquals( JsonHelper.createJsonFrom( Collections.emptyMap() ), stream.toString() );
}
@Test
public void canFormatObjectWithStringField() throws Exception
{
json.assemble( new MappingRepresentation( "string" )
{
@Override
protected void serialize( MappingSerializer serializer )
{
serializer.putString( "key", "expected string" );
}
} );
assertEquals( JsonHelper.createJsonFrom( Collections.singletonMap( "key", "expected string" ) ), stream.toString() );
}
@Test
public void canFormatObjectWithUriField() throws Exception
{
json.assemble( new MappingRepresentation( "uri" )
{
@Override
protected void serialize( MappingSerializer serializer )
{
serializer.putUri( "URL", "subpath" );
}
} );
assertEquals( JsonHelper.createJsonFrom( Collections.singletonMap( "URL", "http://localhost/subpath" ) ),
stream.toString() );
}
@Test
public void canFormatObjectWithNestedObject() throws Exception
{
json.assemble( new MappingRepresentation( "nesting" )
{
@Override
protected void serialize( MappingSerializer serializer )
{
serializer.putMapping( "nested", new MappingRepresentation( "data" )
{
@Override
protected void serialize( MappingSerializer nested )
{
nested.putString( "data", "expected data" );
}
} );
}
} );
assertEquals(
JsonHelper.createJsonFrom( Collections.singletonMap( "nested",
Collections.singletonMap( "data", "expected data" ) ) ), stream.toString() );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_repr_formats_StreamingJsonFormatTest.java
|
2,685
|
@Ignore
public class StreamingJsonFormatPerformanceTest {
public static final String QUERY = "start n=node(*) match p=n-[r:TYPE]->m return n,r,m,p";
private GraphDatabaseService gdb;
private WrappingNeoServer server;
@Before
public void setUp() {
gdb = new TestGraphDatabaseFactory().newImpermanentDatabase();
for ( int i = 0; i < 10; i++ ) {
createData();
}
server = new WrappingNeoServer( (AbstractGraphDatabase) gdb );
server.start();
}
@After
public void tearDown() throws Exception {
server.stop();
}
@Test
public void testStreamCypherResults() throws Exception {
final String query = "{\"query\":\"" + QUERY + "\"}";
measureQueryTime(query);
}
private long measureQueryTime(String query) throws IOException {
final URI baseUri = server.baseUri();
final URL url = new URL(baseUri.toURL(), "db/data/cypher");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json; stream=true");
OutputStream os = connection.getOutputStream();
os.write(query.getBytes());
os.close();
final InputStream input = new BufferedInputStream(connection.getInputStream());
long time=System.currentTimeMillis();
//final CountingInputStream counter = new CountingInputStream(input);
while (input.read()!=-1);
input.close();
final long delta = System.currentTimeMillis() - time;
//System.out.println("result.length() = " + counter.getCount()+" took "+ delta +" ms.");
System.out.println(" took "+ delta +" ms.");
return delta;
}
private void createData() {
final Transaction tx = gdb.beginTx();
try {
final DynamicRelationshipType TYPE = DynamicRelationshipType.withName("TYPE");
Node last = gdb.createNode();
last.setProperty("id", 0);
for (int i = 1; i < 10000; i++) {
final Node node = gdb.createNode();
last.setProperty("id", i);
node.createRelationshipTo(last, TYPE);
last = node;
}
tx.success();
} finally {
tx.finish();
}
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_repr_formats_StreamingJsonFormatPerformanceTest.java
|
2,686
|
public static class StreamingRepresentationFormat extends RepresentationFormat
{
private final JsonGenerator g;
private final InputFormat inputFormat;
public StreamingRepresentationFormat( JsonGenerator g, InputFormat inputFormat )
{
super( StreamingFormat.MEDIA_TYPE );
this.g = g;
this.inputFormat = inputFormat;
}
public StreamingRepresentationFormat usePrettyPrinter()
{
g.useDefaultPrettyPrinter();
return this;
}
@Override
protected String serializeValue( String type, Object value )
{
try
{
g.writeObject( value );
return null;
}
catch ( IOException e )
{
throw new WebApplicationException( e );
}
}
@Override
protected ListWriter serializeList( String type )
{
return new StreamingListWriter( g );
}
@Override
public MappingWriter serializeMapping( String type )
{
return new StreamingMappingWriter( g );
}
@Override
protected String complete( ListWriter serializer )
{
flush();
return null; // already done in done()
}
@Override
protected String complete( MappingWriter serializer )
{
flush();
return null; // already done in done()
}
private void flush()
{
try
{
g.flush();
}
catch ( IOException e )
{
throw new WebApplicationException( e );
}
}
@Override
public Object readValue( String input ) throws BadInputException
{
return inputFormat.readValue( input );
}
@Override
public Map<String, Object> readMap( String input, String... requiredKeys ) throws BadInputException
{
return inputFormat.readMap( input, requiredKeys );
}
@Override
public List<Object> readList( String input ) throws BadInputException
{
return inputFormat.readList( input );
}
@Override
public URI readUri( String input ) throws BadInputException
{
return inputFormat.readUri( input );
}
@Override
public void complete()
{
try
{
// todo only if needed
g.flush();
}
catch ( IOException e )
{
throw new WebApplicationException( e );
}
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_formats_StreamingJsonFormat.java
|
2,687
|
private static class StreamingMappingWriter extends MappingWriter
{
private final JsonGenerator g;
public StreamingMappingWriter( JsonGenerator g )
{
this.g = g;
try
{
g.writeStartObject();
}
catch ( IOException e )
{
throw new WebApplicationException( e );
}
}
public StreamingMappingWriter( JsonGenerator g, String key )
{
this.g = g;
try
{
g.writeObjectFieldStart( key );
}
catch ( IOException e )
{
throw new WebApplicationException( e );
}
}
@Override
public MappingWriter newMapping( String type, String key )
{
return new StreamingMappingWriter( g, key );
}
@Override
public ListWriter newList( String type, String key )
{
return new StreamingListWriter( g, key );
}
@Override
public void writeValue( String type, String key, Object value )
{
try
{
g.writeObjectField( key, value ); // todo individual fields
}
catch ( IOException e )
{
throw new WebApplicationException( e );
}
}
@Override
public void done()
{
try
{
g.writeEndObject();
}
catch ( IOException e )
{
throw new WebApplicationException( e );
}
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_formats_StreamingJsonFormat.java
|
2,688
|
private static class StreamingListWriter extends ListWriter
{
private final JsonGenerator g;
public StreamingListWriter( JsonGenerator g )
{
this.g = g;
try
{
g.writeStartArray();
}
catch ( IOException e )
{
throw new WebApplicationException( e );
}
}
public StreamingListWriter( JsonGenerator g, String key )
{
this.g = g;
try
{
g.writeArrayFieldStart( key );
}
catch ( IOException e )
{
throw new WebApplicationException( e );
}
}
@Override
public MappingWriter newMapping( String type )
{
return new StreamingMappingWriter( g );
}
@Override
public ListWriter newList( String type )
{
return new StreamingListWriter( g );
}
@Override
public void writeValue( String type, Object value )
{
try
{
g.writeObject( value );
}
catch ( IOException e )
{
throw new WebApplicationException( e );
}
}
@Override
public void done()
{
try
{
g.writeEndArray();
}
catch ( IOException e )
{
throw new WebApplicationException( e );
}
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_formats_StreamingJsonFormat.java
|
2,689
|
{
@Override
protected JsonGenerator _createUTF8JsonGenerator( OutputStream out, IOContext ctxt ) throws IOException
{
final int bufferSize = 1024 * 8;
Utf8Generator gen = new Utf8Generator( ctxt, _generatorFeatures, _objectCodec, out,
new byte[bufferSize], 0, true );
if ( _characterEscapes != null )
{
gen.setCharacterEscapes( _characterEscapes );
}
return gen;
}
};
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_formats_StreamingJsonFormat.java
|
2,690
|
@Service.Implementation(RepresentationFormat.class)
public class StreamingJsonFormat extends RepresentationFormat implements StreamingFormat
{
private final JsonFactory factory;
public StreamingJsonFormat()
{
super( MEDIA_TYPE );
this.factory = createJsonFactory();
}
private JsonFactory createJsonFactory()
{
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.getSerializationConfig().disable( SerializationConfig.Feature.FLUSH_AFTER_WRITE_VALUE );
JsonFactory factory = new JsonFactory( objectMapper )
{
@Override
protected JsonGenerator _createUTF8JsonGenerator( OutputStream out, IOContext ctxt ) throws IOException
{
final int bufferSize = 1024 * 8;
Utf8Generator gen = new Utf8Generator( ctxt, _generatorFeatures, _objectCodec, out,
new byte[bufferSize], 0, true );
if ( _characterEscapes != null )
{
gen.setCharacterEscapes( _characterEscapes );
}
return gen;
}
};
factory.enable( JsonGenerator.Feature.FLUSH_PASSED_TO_STREAM );
return factory;
}
@Override
public StreamingRepresentationFormat writeTo( OutputStream output )
{
try
{
JsonGenerator g = factory.createJsonGenerator( output );
return new StreamingRepresentationFormat( g, this );
}
catch ( IOException e )
{
throw new WebApplicationException( e );
}
}
@Override
protected ListWriter serializeList( String type )
{
throw new UnsupportedOperationException();
}
@Override
protected String complete( ListWriter serializer )
{
throw new UnsupportedOperationException();
}
@Override
protected MappingWriter serializeMapping( String type )
{
throw new UnsupportedOperationException();
}
@Override
protected String complete( MappingWriter serializer )
{
throw new UnsupportedOperationException();
}
@Override
protected String serializeValue( String type, Object value )
{
throw new UnsupportedOperationException();
}
private boolean empty( String input )
{
return input == null || "".equals( input.trim() );
}
@Override
public Map<String, Object> readMap( String input, String... requiredKeys ) throws BadInputException
{
if ( empty( input ) )
{
return DefaultFormat.validateKeys( Collections.<String, Object>emptyMap(), requiredKeys );
}
try
{
return DefaultFormat.validateKeys( JsonHelper.jsonToMap( stripByteOrderMark( input ) ), requiredKeys );
}
catch ( Exception ex )
{
throw new BadInputException( ex );
}
}
@Override
public List<Object> readList( String input )
{
// TODO tobias: Implement readList() [Dec 10, 2010]
throw new UnsupportedOperationException( "Not implemented: JsonInput.readList()" );
}
@Override
public Object readValue( String input ) throws BadInputException
{
if ( empty( input ) )
{
return Collections.emptyMap();
}
try
{
return JsonHelper.jsonToSingleValue( stripByteOrderMark( input ) );
}
catch ( JsonParseException ex )
{
throw new BadInputException( ex );
}
}
@Override
public URI readUri( String input ) throws BadInputException
{
try
{
return new URI( readValue( input ).toString() );
}
catch ( URISyntaxException e )
{
throw new BadInputException( e );
}
}
private String stripByteOrderMark( String string )
{
if ( string != null && string.length() > 0 && string.charAt( 0 ) == 0xfeff )
{
return string.substring( 1 );
}
return string;
}
private static class StreamingMappingWriter extends MappingWriter
{
private final JsonGenerator g;
public StreamingMappingWriter( JsonGenerator g )
{
this.g = g;
try
{
g.writeStartObject();
}
catch ( IOException e )
{
throw new WebApplicationException( e );
}
}
public StreamingMappingWriter( JsonGenerator g, String key )
{
this.g = g;
try
{
g.writeObjectFieldStart( key );
}
catch ( IOException e )
{
throw new WebApplicationException( e );
}
}
@Override
public MappingWriter newMapping( String type, String key )
{
return new StreamingMappingWriter( g, key );
}
@Override
public ListWriter newList( String type, String key )
{
return new StreamingListWriter( g, key );
}
@Override
public void writeValue( String type, String key, Object value )
{
try
{
g.writeObjectField( key, value ); // todo individual fields
}
catch ( IOException e )
{
throw new WebApplicationException( e );
}
}
@Override
public void done()
{
try
{
g.writeEndObject();
}
catch ( IOException e )
{
throw new WebApplicationException( e );
}
}
}
private static class StreamingListWriter extends ListWriter
{
private final JsonGenerator g;
public StreamingListWriter( JsonGenerator g )
{
this.g = g;
try
{
g.writeStartArray();
}
catch ( IOException e )
{
throw new WebApplicationException( e );
}
}
public StreamingListWriter( JsonGenerator g, String key )
{
this.g = g;
try
{
g.writeArrayFieldStart( key );
}
catch ( IOException e )
{
throw new WebApplicationException( e );
}
}
@Override
public MappingWriter newMapping( String type )
{
return new StreamingMappingWriter( g );
}
@Override
public ListWriter newList( String type )
{
return new StreamingListWriter( g );
}
@Override
public void writeValue( String type, Object value )
{
try
{
g.writeObject( value );
}
catch ( IOException e )
{
throw new WebApplicationException( e );
}
}
@Override
public void done()
{
try
{
g.writeEndArray();
}
catch ( IOException e )
{
throw new WebApplicationException( e );
}
}
}
public static class StreamingRepresentationFormat extends RepresentationFormat
{
private final JsonGenerator g;
private final InputFormat inputFormat;
public StreamingRepresentationFormat( JsonGenerator g, InputFormat inputFormat )
{
super( StreamingFormat.MEDIA_TYPE );
this.g = g;
this.inputFormat = inputFormat;
}
public StreamingRepresentationFormat usePrettyPrinter()
{
g.useDefaultPrettyPrinter();
return this;
}
@Override
protected String serializeValue( String type, Object value )
{
try
{
g.writeObject( value );
return null;
}
catch ( IOException e )
{
throw new WebApplicationException( e );
}
}
@Override
protected ListWriter serializeList( String type )
{
return new StreamingListWriter( g );
}
@Override
public MappingWriter serializeMapping( String type )
{
return new StreamingMappingWriter( g );
}
@Override
protected String complete( ListWriter serializer )
{
flush();
return null; // already done in done()
}
@Override
protected String complete( MappingWriter serializer )
{
flush();
return null; // already done in done()
}
private void flush()
{
try
{
g.flush();
}
catch ( IOException e )
{
throw new WebApplicationException( e );
}
}
@Override
public Object readValue( String input ) throws BadInputException
{
return inputFormat.readValue( input );
}
@Override
public Map<String, Object> readMap( String input, String... requiredKeys ) throws BadInputException
{
return inputFormat.readMap( input, requiredKeys );
}
@Override
public List<Object> readList( String input ) throws BadInputException
{
return inputFormat.readList( input );
}
@Override
public URI readUri( String input ) throws BadInputException
{
return inputFormat.readUri( input );
}
@Override
public void complete()
{
try
{
// todo only if needed
g.flush();
}
catch ( IOException e )
{
throw new WebApplicationException( e );
}
}
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_formats_StreamingJsonFormat.java
|
2,691
|
public class NullFormat extends RepresentationFormat
{
private final Collection<MediaType> supported;
private final MediaType[] requested;
public NullFormat( Collection<MediaType> supported, MediaType... requested )
{
super( null );
this.supported = supported;
this.requested = requested;
}
@Override
public Object readValue( String input )
{
if ( empty( input ) )
{
return null;
}
throw new MediaTypeNotSupportedException( Response.Status.UNSUPPORTED_MEDIA_TYPE, supported, requested );
}
@Override
public URI readUri( String input )
{
if ( empty( input ) )
{
return null;
}
throw new MediaTypeNotSupportedException( Response.Status.UNSUPPORTED_MEDIA_TYPE, supported, requested );
}
@Override
public Map<String, Object> readMap( String input, String... requiredKeys ) throws BadInputException
{
if ( empty( input ) )
{
if ( requiredKeys.length != 0 )
{
String missingKeys = Arrays.toString( requiredKeys );
throw new BadInputException( "Missing required keys: " + missingKeys );
}
return Collections.emptyMap();
}
throw new MediaTypeNotSupportedException( Response.Status.UNSUPPORTED_MEDIA_TYPE, supported, requested );
}
@Override
public List<Object> readList( String input )
{
if ( empty( input ) )
{
return Collections.emptyList();
}
throw new MediaTypeNotSupportedException( Response.Status.UNSUPPORTED_MEDIA_TYPE, supported, requested );
}
private boolean empty( String input )
{
return input == null || "".equals( input.trim() );
}
@Override
protected String serializeValue( final String type, final Object value )
{
throw new MediaTypeNotSupportedException( Response.Status.NOT_ACCEPTABLE, supported, requested );
}
@Override
protected ListWriter serializeList( final String type )
{
throw new MediaTypeNotSupportedException( Response.Status.NOT_ACCEPTABLE, supported, requested );
}
@Override
protected MappingWriter serializeMapping( final String type )
{
throw new MediaTypeNotSupportedException( Response.Status.NOT_ACCEPTABLE, supported, requested );
}
@Override
protected String complete( final ListWriter serializer )
{
throw new MediaTypeNotSupportedException( Response.Status.NOT_ACCEPTABLE, supported, requested );
}
@Override
protected String complete( final MappingWriter serializer )
{
throw new MediaTypeNotSupportedException( Response.Status.NOT_ACCEPTABLE, supported, requested );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_formats_NullFormat.java
|
2,692
|
public class MapWrappingWriter extends MappingWriter
{
final Map<String, Object> data;
final boolean interactive;
public MapWrappingWriter( Map<String, Object> data )
{
this( data, false );
}
public MapWrappingWriter( Map<String, Object> data, boolean interactive )
{
this.data = data;
this.interactive = interactive;
}
@Override
final protected boolean isInteractive()
{
return interactive;
}
@Override
protected ListWriter newList( String type, String key )
{
List<Object> list = new ArrayList<Object>();
data.put( key, list );
return new ListWrappingWriter( list, interactive );
}
@Override
protected MappingWriter newMapping( String type, String key )
{
Map<String, Object> map = new HashMap<String, Object>();
data.put( key, map );
return new MapWrappingWriter( map, interactive );
}
@Override
protected void writeValue( String type, String key, Object value )
{
data.put( key, value );
}
@Override
protected void done()
{
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_formats_MapWrappingWriter.java
|
2,693
|
public class ListWrappingWriter extends ListWriter
{
final List<Object> data;
private final boolean interactive;
public ListWrappingWriter( List<Object> data )
{
this( data, false );
}
ListWrappingWriter( List<Object> data, boolean interactive )
{
this.data = data;
this.interactive = interactive;
}
@Override
protected ListWriter newList( String type )
{
List<Object> list = new ArrayList<Object>();
data.add( list );
return new ListWrappingWriter( list, interactive );
}
@Override
protected MappingWriter newMapping( String type )
{
Map<String, Object> map = new HashMap<String, Object>();
data.add( map );
return new MapWrappingWriter( map, interactive );
}
@Override
protected void writeValue( String type, Object value )
{
data.add( value );
}
@Override
protected void done()
{
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_repr_formats_ListWrappingWriter.java
|
2,694
|
public class TransactionFacade
{
private final TransitionalPeriodTransactionMessContainer kernel;
private final ExecutionEngine engine;
private final TransactionRegistry registry;
private final StringLogger log;
private final URI baseUri;
public TransactionFacade( TransitionalPeriodTransactionMessContainer kernel, ExecutionEngine engine,
TransactionRegistry registry, URI baseUri, StringLogger log )
{
this.kernel = kernel;
this.engine = engine;
this.registry = registry;
this.log = log;
try {
this.baseUri = new URI(baseUri+"db/data");
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
public TransactionHandle newTransactionHandle( TransactionUriScheme uriScheme ) throws TransactionLifecycleException
{
return new TransactionHandle( kernel, engine, registry, uriScheme, log );
}
public TransactionHandle findTransactionHandle( long txId ) throws TransactionLifecycleException
{
return registry.acquire( txId );
}
public StatementDeserializer deserializer( InputStream input )
{
return new StatementDeserializer( input );
}
public ExecutionResultSerializer serializer( OutputStream output )
{
return new ExecutionResultSerializer( output, baseUri, log );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_transactional_TransactionFacade.java
|
2,695
|
{
@Override
public RequestDispatcher create( AbstractResourceMethod abstractResourceMethod )
{
final RequestDispatcher requestDispatcher = resourceMethodDispatchProvider.create(
abstractResourceMethod );
return new TransactionalRequestDispatcher( database, requestDispatcher );
}
};
| false
|
community_server_src_main_java_org_neo4j_server_rest_transactional_TransactionFilter.java
|
2,696
|
public class JmxServiceDocIT extends AbstractRestFunctionalTestBase
{
private static FunctionalTestHelper functionalTestHelper;
@BeforeClass
public static void setupServer() throws IOException
{
functionalTestHelper = new FunctionalTestHelper( server() );
}
@Before
public void cleanTheDatabase()
{
cleanDatabase();
}
@Test
public void shouldRespondWithTheWebAdminClientSettings() throws Exception {
String url = functionalTestHelper.managementUri() + "/server/jmx";
JaxRsResponse resp = RestRequest.req().get(url);
String json = resp.getEntity();
assertEquals(json, 200, resp.getStatus());
assertThat(json, containsString("resources"));
assertThat(json, containsString("jmx/domain/{domain}/{objectName}"));
resp.close();
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_JmxServiceDocIT.java
|
2,697
|
@Path( "/relationship/types" )
public class DatabaseMetadataService
{
private final Database database;
private RepresentationWriteHandler representationWriteHandler = RepresentationWriteHandler.DO_NOTHING;
public DatabaseMetadataService( @Context Database database )
{
this.database = database;
}
@GET
@Produces( MediaType.APPLICATION_JSON )
public Response getRelationshipTypes()
{
try
{
Iterable<RelationshipType> relationshipTypes = GlobalGraphOperations.at( database.getGraph() ).getAllRelationshipTypes();
return Response.ok()
.type( MediaType.APPLICATION_JSON )
.entity( generateJsonRepresentation( relationshipTypes ) )
.build();
}
finally
{
representationWriteHandler.onRepresentationFinal();
}
}
private String generateJsonRepresentation( Iterable<RelationshipType> relationshipTypes )
{
StringBuilder sb = new StringBuilder();
sb.append( "[" );
for ( RelationshipType rt : relationshipTypes )
{
sb.append( "\"" );
sb.append( rt.name() );
sb.append( "\"," );
}
sb.append( "]" );
return sb.toString()
.replaceAll( ",]", "]" );
}
public void setRepresentationWriteHandler( RepresentationWriteHandler representationWriteHandler )
{
this.representationWriteHandler = representationWriteHandler;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_web_DatabaseMetadataService.java
|
2,698
|
public class DatabaseActionsTest
{
private static GraphDbHelper graphdbHelper;
private static Database database;
private static AbstractGraphDatabase graph;
private static DatabaseActions actions;
@BeforeClass
public static void createDb() throws IOException
{
graph = (AbstractGraphDatabase) new TestGraphDatabaseFactory().newImpermanentDatabase();
database = new WrappedDatabase( graph );
graphdbHelper = new GraphDbHelper( database );
actions = new TransactionWrappedDatabaseActions( new LeaseManager( new FakeClock() ), ForceMode.forced,
database.getGraph() );
}
@AfterClass
public static void shutdownDatabase() throws Throwable
{
graph.shutdown();
}
@After
public void clearDb()
{
ServerHelper.cleanTheDatabase( graph );
}
private long createNode( Map<String, Object> properties )
{
long nodeId;
Transaction tx = database.getGraph().beginTx();
try
{
Node node = database.getGraph().createNode();
for ( Map.Entry<String, Object> entry : properties.entrySet() )
{
node.setProperty( entry.getKey(), entry.getValue() );
}
nodeId = node.getId();
tx.success();
}
finally
{
tx.finish();
}
return nodeId;
}
@Test
public void createdNodeShouldBeInDatabase() throws Exception
{
NodeRepresentation noderep = actions.createNode( Collections.<String, Object>emptyMap() );
Transaction tx = database.getGraph().beginTx();
try
{
assertNotNull( database.getGraph().getNodeById( noderep.getId() ) );
}
finally
{
tx.finish();
}
}
@Test
public void nodeInDatabaseShouldBeRetrievable() throws NodeNotFoundException
{
long nodeId = new GraphDbHelper( database ).createNode();
assertNotNull( actions.getNode( nodeId ) );
}
@Test
public void shouldBeAbleToStorePropertiesInAnExistingNode() throws
PropertyValueException, NodeNotFoundException
{
long nodeId = graphdbHelper.createNode();
Map<String, Object> properties = new HashMap<String, Object>();
properties.put( "foo", "bar" );
properties.put( "baz", 17 );
actions.setAllNodeProperties( nodeId, properties );
Transaction tx = database.getGraph().beginTx();
try
{
Node node = database.getGraph().getNodeById( nodeId );
assertHasProperties( node, properties );
}
finally
{
tx.finish();
}
}
@Test(expected = PropertyValueException.class)
public void shouldFailOnTryingToStoreMixedArraysAsAProperty() throws Exception
{
long nodeId = graphdbHelper.createNode();
Map<String, Object> properties = new HashMap<String, Object>();
Object[] dodgyArray = new Object[3];
dodgyArray[0] = 0;
dodgyArray[1] = 1;
dodgyArray[2] = "two";
properties.put( "foo", dodgyArray );
actions.setAllNodeProperties( nodeId, properties );
}
@Test
public void shouldOverwriteExistingProperties() throws PropertyValueException,
NodeNotFoundException
{
long nodeId;
Transaction tx = database.getGraph().beginTx();
try
{
Node node = database.getGraph().createNode();
node.setProperty( "remove me", "trash" );
nodeId = node.getId();
tx.success();
}
finally
{
tx.finish();
}
Map<String, Object> properties = new HashMap<String, Object>();
properties.put( "foo", "bar" );
properties.put( "baz", 17 );
actions.setAllNodeProperties( nodeId, properties );
tx = database.getGraph().beginTx();
try
{
Node node = database.getGraph().getNodeById( nodeId );
assertHasProperties( node, properties );
assertNull( node.getProperty( "remove me", null ) );
}
finally
{
tx.finish();
}
}
@Test
public void shouldBeAbleToGetPropertiesOnNode() throws NodeNotFoundException
{
long nodeId;
Map<String, Object> properties = new HashMap<String, Object>();
properties.put( "foo", "bar" );
properties.put( "neo", "Thomas A. Anderson" );
properties.put( "number", 15L );
Transaction tx = database.getGraph().beginTx();
Node node;
try
{
node = database.getGraph().createNode();
for ( Map.Entry<String, Object> entry : properties.entrySet() )
{
node.setProperty( entry.getKey(), entry.getValue() );
}
nodeId = node.getId();
tx.success();
}
finally
{
tx.finish();
}
Transaction transaction = graph.beginTx();
try
{
assertEquals( properties, serialize( actions.getAllNodeProperties( nodeId ) ) );
}
finally
{
transaction.finish();
}
}
@Test
public void shouldRemoveNodeWithNoRelationsFromDBOnDelete() throws NodeNotFoundException,
OperationFailureException
{
long nodeId;
Transaction tx = database.getGraph().beginTx();
try
{
Node node = database.getGraph().createNode();
nodeId = node.getId();
tx.success();
}
finally
{
tx.finish();
}
int nodeCount = graphdbHelper.getNumberOfNodes();
actions.deleteNode( nodeId );
assertEquals( nodeCount - 1, graphdbHelper.getNumberOfNodes() );
}
@Test
public void shouldBeAbleToSetPropertyOnNode() throws Exception
{
long nodeId = createNode( Collections.<String, Object>emptyMap() );
String key = "foo";
Object value = "bar";
actions.setNodeProperty( nodeId, key, value );
assertEquals( Collections.singletonMap( key, value ), graphdbHelper.getNodeProperties( nodeId ) );
}
@Test
public void settingAnEmptyArrayShouldWorkIfOriginalEntityHasAnEmptyArrayAsWell() throws Exception
{
// Given
long nodeId = createNode( map( "emptyArray", new int[]{} ) );
// When
actions.setNodeProperty( nodeId, "emptyArray", new ArrayList<>() );
// Then
Transaction transaction = graph.beginTx();
try
{
assertThat( ((List<Object>) serialize( actions.getNodeProperty( nodeId, "emptyArray" ) )).size(), is( 0 ) );
}
finally
{
transaction.finish();
}
}
@Test
public void shouldBeAbleToGetPropertyOnNode() throws Exception
{
String key = "foo";
Object value = "bar";
long nodeId = createNode( Collections.singletonMap( key, value ) );
Transaction transaction = graph.beginTx();
try
{
assertEquals( value, serialize( actions.getNodeProperty( nodeId, key ) ) );
}
finally
{
transaction.finish();
}
}
@Test
public void shouldBeAbleToRemoveNodeProperties() throws Exception
{
Map<String, Object> properties = new HashMap<String, Object>();
properties.put( "foo", "bar" );
properties.put( "number", 15 );
long nodeId = createNode( properties );
actions.removeAllNodeProperties( nodeId );
Transaction tx = database.getGraph().beginTx();
try
{
Node node = database.getGraph().getNodeById( nodeId );
assertEquals( false, node.getPropertyKeys()
.iterator()
.hasNext() );
tx.success();
}
finally
{
tx.finish();
}
}
@Test
public void shouldStoreRelationshipsBetweenTwoExistingNodes() throws Exception
{
int relationshipCount = graphdbHelper.getNumberOfRelationships();
actions.createRelationship( graphdbHelper.createNode(), graphdbHelper.createNode(), "LOVES",
Collections.<String, Object>emptyMap() );
assertEquals( relationshipCount + 1, graphdbHelper.getNumberOfRelationships() );
}
@Test
public void shouldStoreSuppliedPropertiesWhenCreatingRelationship() throws Exception
{
Map<String, Object> properties = new HashMap<String, Object>();
properties.put( "string", "value" );
properties.put( "integer", 17 );
long relId = actions.createRelationship( graphdbHelper.createNode(), graphdbHelper.createNode(), "LOVES",
properties )
.getId();
Transaction tx = database.getGraph().beginTx();
try
{
Relationship rel = database.getGraph().getRelationshipById( relId );
for ( String key : rel.getPropertyKeys() )
{
assertTrue( "extra property stored", properties.containsKey( key ) );
}
for ( Map.Entry<String, Object> entry : properties.entrySet() )
{
assertEquals( entry.getValue(), rel.getProperty( entry.getKey() ) );
}
}
finally
{
tx.finish();
}
}
@Test
public void shouldNotCreateRelationshipBetweenNonExistentNodes() throws Exception
{
long nodeId = graphdbHelper.createNode();
Map<String, Object> properties = Collections.emptyMap();
try
{
actions.createRelationship( nodeId, nodeId * 1000, "Loves", properties );
fail();
}
catch ( EndNodeNotFoundException e )
{
// ok
}
try
{
actions.createRelationship( nodeId * 1000, nodeId, "Loves", properties );
fail();
}
catch ( StartNodeNotFoundException e )
{
// ok
}
}
@Test
public void shouldAllowCreateRelationshipWithSameStartAsEndNode() throws Exception
{
long nodeId = graphdbHelper.createNode();
Map<String, Object> properties = Collections.emptyMap();
RelationshipRepresentation rel = actions.createRelationship( nodeId, nodeId, "Loves", properties );
assertNotNull( rel );
}
@Test
public void shouldBeAbleToRemoveNodeProperty() throws Exception
{
Map<String, Object> properties = new HashMap<String, Object>();
properties.put( "foo", "bar" );
properties.put( "number", 15 );
long nodeId = createNode( properties );
actions.removeNodeProperty( nodeId, "foo" );
Transaction tx = database.getGraph().beginTx();
try
{
Node node = database.getGraph().getNodeById( nodeId );
assertEquals( 15, node.getProperty( "number" ) );
assertEquals( false, node.hasProperty( "foo" ) );
tx.success();
}
finally
{
tx.finish();
}
}
@Test
public void shouldReturnTrueIfNodePropertyRemoved() throws Exception
{
Map<String, Object> properties = new HashMap<String, Object>();
properties.put( "foo", "bar" );
properties.put( "number", 15 );
long nodeId = createNode( properties );
actions.removeNodeProperty( nodeId, "foo" );
}
@Test(expected = NoSuchPropertyException.class)
public void shouldReturnFalseIfNodePropertyNotRemoved() throws Exception
{
Map<String, Object> properties = new HashMap<String, Object>();
properties.put( "foo", "bar" );
properties.put( "number", 15 );
long nodeId = createNode( properties );
actions.removeNodeProperty( nodeId, "baz" );
}
@Test
public void shouldBeAbleToRetrieveARelationship() throws Exception
{
long relationship = graphdbHelper.createRelationship( "ENJOYED" );
assertNotNull( actions.getRelationship( relationship ) );
}
@Test
public void shouldBeAbleToGetPropertiesOnRelationship() throws Exception
{
long relationshipId;
Map<String, Object> properties = new HashMap<String, Object>();
properties.put( "foo", "bar" );
properties.put( "neo", "Thomas A. Anderson" );
properties.put( "number", 15L );
Transaction tx = database.getGraph().beginTx();
try
{
Node startNode = database.getGraph().createNode();
Node endNode = database.getGraph().createNode();
Relationship relationship = startNode.createRelationshipTo( endNode,
DynamicRelationshipType.withName( "knows" ) );
for ( Map.Entry<String, Object> entry : properties.entrySet() )
{
relationship.setProperty( entry.getKey(), entry.getValue() );
}
relationshipId = relationship.getId();
tx.success();
}
finally
{
tx.finish();
}
Transaction transaction = graph.beginTx();
try
{
assertEquals( properties, serialize( actions.getAllRelationshipProperties( relationshipId ) ) );
}
finally
{
transaction.finish();
}
}
@Test
public void shouldBeAbleToRetrieveASinglePropertyFromARelationship() throws Exception
{
Map<String, Object> properties = new HashMap<String, Object>();
properties.put( "foo", "bar" );
properties.put( "neo", "Thomas A. Anderson" );
properties.put( "number", 15L );
long relationshipId = graphdbHelper.createRelationship( "LOVES" );
graphdbHelper.setRelationshipProperties( relationshipId, properties );
Transaction transaction = graph.beginTx();
Object relationshipProperty;
try
{
relationshipProperty = serialize( actions.getRelationshipProperty( relationshipId, "foo" ) );
}
finally
{
transaction.finish();
}
assertEquals( "bar", relationshipProperty );
}
@Test
public void shouldBeAbleToDeleteARelationship() throws Exception
{
long relationshipId = graphdbHelper.createRelationship( "LOVES" );
actions.deleteRelationship( relationshipId );
try
{
graphdbHelper.getRelationship( relationshipId );
fail();
}
catch ( NotFoundException e )
{
}
}
@Test
public void shouldBeAbleToRetrieveRelationshipsFromNode() throws Exception
{
long nodeId = graphdbHelper.createNode();
graphdbHelper.createRelationship( "LIKES", nodeId, graphdbHelper.createNode() );
graphdbHelper.createRelationship( "LIKES", graphdbHelper.createNode(), nodeId );
graphdbHelper.createRelationship( "HATES", nodeId, graphdbHelper.createNode() );
Transaction transaction = graph.beginTx();
try
{
verifyRelReps( 3,
actions.getNodeRelationships( nodeId, RelationshipDirection.all,
Collections.<String>emptyList() ) );
verifyRelReps( 1,
actions.getNodeRelationships( nodeId, RelationshipDirection.in, Collections.<String>emptyList() ) );
verifyRelReps( 2,
actions.getNodeRelationships( nodeId, RelationshipDirection.out,
Collections.<String>emptyList() ) );
verifyRelReps( 3,
actions.getNodeRelationships( nodeId, RelationshipDirection.all, Arrays.asList( "LIKES",
"HATES" ) ) );
verifyRelReps( 1,
actions.getNodeRelationships( nodeId, RelationshipDirection.in, Arrays.asList( "LIKES",
"HATES" ) ) );
verifyRelReps( 2,
actions.getNodeRelationships( nodeId, RelationshipDirection.out, Arrays.asList( "LIKES",
"HATES" ) ) );
verifyRelReps( 2, actions.getNodeRelationships( nodeId, RelationshipDirection.all,
Arrays.asList( "LIKES" ) ) );
verifyRelReps( 1, actions.getNodeRelationships( nodeId, RelationshipDirection.in,
Arrays.asList( "LIKES" ) ) );
verifyRelReps( 1, actions.getNodeRelationships( nodeId, RelationshipDirection.out,
Arrays.asList( "LIKES" ) ) );
verifyRelReps( 1, actions.getNodeRelationships( nodeId, RelationshipDirection.all,
Arrays.asList( "HATES" ) ) );
verifyRelReps( 0, actions.getNodeRelationships( nodeId, RelationshipDirection.in,
Arrays.asList( "HATES" ) ) );
verifyRelReps( 1, actions.getNodeRelationships( nodeId, RelationshipDirection.out,
Arrays.asList( "HATES" ) ) );
}
finally
{
transaction.finish();
}
}
@Test
public void shouldNotGetAnyRelationshipsWhenRetrievingFromNodeWithoutRelationships() throws Exception
{
long nodeId = graphdbHelper.createNode();
Transaction transaction = graph.beginTx();
try
{
verifyRelReps( 0,
actions.getNodeRelationships( nodeId, RelationshipDirection.all,
Collections.<String>emptyList() ) );
verifyRelReps( 0,
actions.getNodeRelationships( nodeId, RelationshipDirection.in,
Collections.<String>emptyList() ) );
verifyRelReps( 0,
actions.getNodeRelationships( nodeId, RelationshipDirection.out,
Collections.<String>emptyList() ) );
}
finally
{
transaction.finish();
}
}
@Test
public void shouldBeAbleToSetRelationshipProperties() throws Exception
{
long relationshipId = graphdbHelper.createRelationship( "KNOWS" );
Map<String, Object> properties = new HashMap<>();
properties.put( "foo", "bar" );
properties.put( "number", 10 );
actions.setAllRelationshipProperties( relationshipId, properties );
assertEquals( properties, graphdbHelper.getRelationshipProperties( relationshipId ) );
}
@Test
public void shouldBeAbleToSetRelationshipProperty() throws Exception
{
long relationshipId = graphdbHelper.createRelationship( "KNOWS" );
String key = "foo";
Object value = "bar";
actions.setRelationshipProperty( relationshipId, key, value );
assertEquals( Collections.singletonMap( key, value ),
graphdbHelper.getRelationshipProperties( relationshipId ) );
}
@Test
public void shouldRemoveRelationProperties() throws Exception
{
long relId = graphdbHelper.createRelationship( "PAIR-PROGRAMS_WITH" );
Map<String, Object> map = new HashMap<String, Object>();
map.put( "foo", "bar" );
map.put( "baz", 22 );
graphdbHelper.setRelationshipProperties( relId, map );
actions.removeAllRelationshipProperties( relId );
assertTrue( graphdbHelper.getRelationshipProperties( relId )
.isEmpty() );
}
@Test
public void shouldRemoveRelationshipProperty() throws Exception
{
long relId = graphdbHelper.createRelationship( "PAIR-PROGRAMS_WITH" );
Map<String, Object> map = new HashMap<String, Object>();
map.put( "foo", "bar" );
map.put( "baz", 22 );
graphdbHelper.setRelationshipProperties( relId, map );
actions.removeRelationshipProperty( relId, "foo" );
assertEquals( 1, graphdbHelper.getRelationshipProperties( relId )
.size() );
}
@SuppressWarnings("unchecked")
private void verifyRelReps( int expectedSize, ListRepresentation repr )
{
List<Object> relreps = serialize( repr );
assertEquals( expectedSize, relreps.size() );
for ( Object relrep : relreps )
{
RelationshipRepresentationTest.verifySerialisation( (Map<String, Object>) relrep );
}
}
private void assertHasProperties( PropertyContainer container, Map<String, Object> properties )
{
for ( Map.Entry<String, Object> entry : properties.entrySet() )
{
assertEquals( entry.getValue(), container.getProperty( entry.getKey() ) );
}
}
@Test
public void shouldBeAbleToIndexNode()
{
String key = "mykey";
String value = "myvalue";
long nodeId = graphdbHelper.createNode();
String indexName = "node";
actions.createNodeIndex( MapUtil.map( "name", indexName ) );
Transaction transaction = graph.beginTx();
List<Object> listOfIndexedNodes;
try
{
listOfIndexedNodes = serialize( actions.getIndexedNodes( indexName, key, value ) );
}
finally
{
transaction.finish();
}
assertFalse( listOfIndexedNodes.iterator().hasNext() );
actions.addToNodeIndex( indexName, key, value, nodeId );
assertEquals( Arrays.asList( nodeId ), graphdbHelper.getIndexedNodes( indexName, key, value ) );
}
@Test
public void shouldBeAbleToFulltextIndex()
{
String key = "key";
String value = "the value with spaces";
long nodeId = graphdbHelper.createNode();
String indexName = "fulltext-node";
graphdbHelper.createNodeFullTextIndex( indexName );
Transaction transaction = graph.beginTx();
try
{
assertFalse( serialize( actions.getIndexedNodes( indexName, key, value ) ).iterator()
.hasNext() );
}
finally
{
transaction.finish();
}
actions.addToNodeIndex( indexName, key, value, nodeId );
assertEquals( Arrays.asList( nodeId ), graphdbHelper.getIndexedNodes( indexName, key, value ) );
assertEquals( Arrays.asList( nodeId ), graphdbHelper.getIndexedNodes( indexName, key,
"the value with spaces" ) );
assertEquals( Arrays.asList( nodeId ), graphdbHelper.queryIndexedNodes( indexName, key, "the" ) );
assertEquals( Arrays.asList( nodeId ), graphdbHelper.queryIndexedNodes( indexName, key, "value" ) );
assertEquals( Arrays.asList( nodeId ), graphdbHelper.queryIndexedNodes( indexName, key, "with" ) );
assertEquals( Arrays.asList( nodeId ), graphdbHelper.queryIndexedNodes( indexName, key, "spaces" ) );
assertEquals( Arrays.asList( nodeId ), graphdbHelper.queryIndexedNodes( indexName, key, "*spaces*" ) );
assertTrue( graphdbHelper.getIndexedNodes( indexName, key, "nohit" ).isEmpty() );
}
@Test
public void shouldGetExtendedNodeRepresentationsWhenGettingFromIndex()
{
String key = "mykey3";
String value = "value";
long nodeId = graphdbHelper.createNode();
String indexName = "node";
graphdbHelper.addNodeToIndex( indexName, key, value, nodeId );
int counter = 0;
Transaction transaction = graph.beginTx();
List<Object> indexedNodes;
try
{
indexedNodes = serialize( actions.getIndexedNodes( indexName, key, value ) );
}
finally
{
transaction.finish();
}
for ( Object indexedNode : indexedNodes )
{
@SuppressWarnings("unchecked")
Map<String, Object> serialized = (Map<String, Object>) indexedNode;
NodeRepresentationTest.verifySerialisation( serialized );
assertNotNull( serialized.get( "indexed" ) );
counter++;
}
assertEquals( 1, counter );
}
@Test
public void shouldBeAbleToRemoveNodeFromIndex()
{
String key = "mykey2";
String value = "myvalue";
String value2 = "myvalue2";
String indexName = "node";
long nodeId = graphdbHelper.createNode();
actions.addToNodeIndex( indexName, key, value, nodeId );
actions.addToNodeIndex( indexName, key, value2, nodeId );
assertEquals( 1, graphdbHelper.getIndexedNodes( indexName, key, value )
.size() );
assertEquals( 1, graphdbHelper.getIndexedNodes( indexName, key, value2 )
.size() );
actions.removeFromNodeIndex( indexName, key, value, nodeId );
assertEquals( 0, graphdbHelper.getIndexedNodes( indexName, key, value )
.size() );
assertEquals( 1, graphdbHelper.getIndexedNodes( indexName, key, value2 )
.size() );
actions.removeFromNodeIndex( indexName, key, value2, nodeId );
assertEquals( 0, graphdbHelper.getIndexedNodes( indexName, key, value )
.size() );
assertEquals( 0, graphdbHelper.getIndexedNodes( indexName, key, value2 )
.size() );
}
@Test
public void shouldBeAbleToRemoveNodeFromIndexWithoutKeyValue()
{
String key1 = "kvkey1";
String key2 = "kvkey2";
String value = "myvalue";
String value2 = "myvalue2";
String indexName = "node";
long nodeId = graphdbHelper.createNode();
actions.addToNodeIndex( indexName, key1, value, nodeId );
actions.addToNodeIndex( indexName, key1, value2, nodeId );
actions.addToNodeIndex( indexName, key2, value, nodeId );
actions.addToNodeIndex( indexName, key2, value2, nodeId );
assertEquals( 1, graphdbHelper.getIndexedNodes( indexName, key1, value )
.size() );
assertEquals( 1, graphdbHelper.getIndexedNodes( indexName, key1, value2 )
.size() );
assertEquals( 1, graphdbHelper.getIndexedNodes( indexName, key2, value )
.size() );
assertEquals( 1, graphdbHelper.getIndexedNodes( indexName, key2, value2 )
.size() );
actions.removeFromNodeIndexNoValue( indexName, key1, nodeId );
assertEquals( 0, graphdbHelper.getIndexedNodes( indexName, key1, value )
.size() );
assertEquals( 0, graphdbHelper.getIndexedNodes( indexName, key1, value2 )
.size() );
assertEquals( 1, graphdbHelper.getIndexedNodes( indexName, key2, value )
.size() );
assertEquals( 1, graphdbHelper.getIndexedNodes( indexName, key2, value2 )
.size() );
actions.removeFromNodeIndexNoKeyValue( indexName, nodeId );
assertEquals( 0, graphdbHelper.getIndexedNodes( indexName, key1, value )
.size() );
assertEquals( 0, graphdbHelper.getIndexedNodes( indexName, key1, value2 )
.size() );
assertEquals( 0, graphdbHelper.getIndexedNodes( indexName, key2, value )
.size() );
assertEquals( 0, graphdbHelper.getIndexedNodes( indexName, key2, value2 )
.size() );
}
private long createBasicTraversableGraph()
{
// (Root)
// / \
// (Mattias) (Johan)
// / / \
// (Emil) (Peter) (Tobias)
long startNode = graphdbHelper.createNode( MapUtil.map( "name", "Root" ) );
long child1_l1 = graphdbHelper.createNode( MapUtil.map( "name", "Mattias" ) );
graphdbHelper.createRelationship( "knows", startNode, child1_l1 );
long child2_l1 = graphdbHelper.createNode( MapUtil.map( "name", "Johan" ) );
graphdbHelper.createRelationship( "knows", startNode, child2_l1 );
long child1_l2 = graphdbHelper.createNode( MapUtil.map( "name", "Emil" ) );
graphdbHelper.createRelationship( "knows", child2_l1, child1_l2 );
long child1_l3 = graphdbHelper.createNode( MapUtil.map( "name", "Peter" ) );
graphdbHelper.createRelationship( "knows", child1_l2, child1_l3 );
long child2_l3 = graphdbHelper.createNode( MapUtil.map( "name", "Tobias" ) );
graphdbHelper.createRelationship( "loves", child1_l2, child2_l3 );
return startNode;
}
private long[] createMoreComplexGraph()
{
// (a)
// / \
// v v
// (b)<---(c) (d)-->(e)
// \ / \ / /
// v v v v /
// (f)--->(g)<----
long a = graphdbHelper.createNode();
long b = graphdbHelper.createNode();
long c = graphdbHelper.createNode();
long d = graphdbHelper.createNode();
long e = graphdbHelper.createNode();
long f = graphdbHelper.createNode();
long g = graphdbHelper.createNode();
graphdbHelper.createRelationship( "to", a, c );
graphdbHelper.createRelationship( "to", a, d );
graphdbHelper.createRelationship( "to", c, b );
graphdbHelper.createRelationship( "to", d, e );
graphdbHelper.createRelationship( "to", b, f );
graphdbHelper.createRelationship( "to", c, f );
graphdbHelper.createRelationship( "to", f, g );
graphdbHelper.createRelationship( "to", d, g );
graphdbHelper.createRelationship( "to", e, g );
graphdbHelper.createRelationship( "to", c, g );
return new long[]{a, g};
}
private void createRelationshipWithProperties( long start, long end, Map<String, Object> properties )
{
long rel = graphdbHelper.createRelationship( "to", start, end );
graphdbHelper.setRelationshipProperties( rel, properties );
}
private long[] createDijkstraGraph( boolean includeOnes )
{
/* Layout:
* (y)
* ^
* [2] _____[1]___
* \ v |
* (start)--[1]->(a)--[9]-->(x)<- (e)--[2]->(f)
* | ^ ^^ \ ^
* [1] ---[7][5][4] -[3] [1]
* v / | / \ /
* (b)--[1]-->(c)--[1]->(d)
*/
Map<String, Object> costOneProperties = includeOnes ? map( "cost", (double) 1 ) : map();
long start = graphdbHelper.createNode();
long a = graphdbHelper.createNode();
long b = graphdbHelper.createNode();
long c = graphdbHelper.createNode();
long d = graphdbHelper.createNode();
long e = graphdbHelper.createNode();
long f = graphdbHelper.createNode();
long x = graphdbHelper.createNode();
long y = graphdbHelper.createNode();
createRelationshipWithProperties( start, a, costOneProperties );
createRelationshipWithProperties( a, x, map( "cost", (double) 9 ) );
createRelationshipWithProperties( a, b, costOneProperties );
createRelationshipWithProperties( b, x, map( "cost", (double) 7 ) );
createRelationshipWithProperties( b, c, costOneProperties );
createRelationshipWithProperties( c, x, map( "cost", (double) 5 ) );
createRelationshipWithProperties( c, x, map( "cost", (double) 4 ) );
createRelationshipWithProperties( c, d, costOneProperties );
createRelationshipWithProperties( d, x, map( "cost", (double) 3 ) );
createRelationshipWithProperties( d, e, costOneProperties );
createRelationshipWithProperties( e, x, costOneProperties );
createRelationshipWithProperties( e, f, map( "cost", (double) 2 ) );
createRelationshipWithProperties( x, y, map( "cost", (double) 2 ) );
return new long[]{start, x};
}
@Test
public void shouldBeAbleToTraverseWithDefaultParameters()
{
long startNode = createBasicTraversableGraph();
Transaction transaction = graph.beginTx();
try
{
assertEquals( 2, serialize( actions.traverse( startNode, new HashMap<String, Object>(),
TraverserReturnType.node ) ).size() );
}
finally
{
transaction.finish();
}
}
@Test
public void shouldBeAbleToTraverseDepthTwo()
{
long startNode = createBasicTraversableGraph();
Transaction transaction = graph.beginTx();
try
{
assertEquals( 3, serialize( actions.traverse( startNode, MapUtil.map( "max_depth", 2 ),
TraverserReturnType.node ) ).size() );
}
finally
{
transaction.finish();
}
}
@Test
public void shouldBeAbleToTraverseEverything()
{
long startNode = createBasicTraversableGraph();
Transaction transaction = graph.beginTx();
try
{
assertEquals( 6, serialize( actions.traverse(
startNode,
MapUtil.map( "return_filter", MapUtil.map( "language", "javascript", "body", "true;" ), "max_depth",
10 ),
TraverserReturnType.node ) ).size() );
assertEquals( 6, serialize( actions.traverse( startNode,
MapUtil.map( "return_filter", MapUtil.map( "language", "builtin", "name", "all" ), "max_depth",
10 ),
TraverserReturnType.node ) ).size() );
}
finally
{
transaction.finish();
}
}
@Test
public void shouldBeAbleToUseCustomReturnFilter()
{
long startNode = createBasicTraversableGraph();
Transaction transaction = graph.beginTx();
try
{
assertEquals( 3, serialize( actions.traverse( startNode, MapUtil.map( "prune_evaluator", MapUtil.map(
"language", "builtin", "name", "none" ), "return_filter", MapUtil.map( "language", "javascript",
"body", "position.endNode().getProperty( 'name' ).contains( 'o' )" ) ), TraverserReturnType.node ) )
.size() );
}
finally
{
transaction.finish();
}
}
@Test
public void shouldBeAbleToTraverseWithMaxDepthAndPruneEvaluatorCombined()
{
long startNode = createBasicTraversableGraph();
Transaction transaction = graph.beginTx();
try
{
assertEquals( 3, serialize( actions.traverse( startNode,
MapUtil.map( "max_depth", 2, "prune_evaluator", MapUtil.map( "language", "javascript", "body",
"position.endNode().getProperty('name').equals('Emil')" ) ),
TraverserReturnType.node ) ).size() );
assertEquals( 2, serialize( actions.traverse( startNode,
MapUtil.map( "max_depth", 1, "prune_evaluator", MapUtil.map( "language", "javascript", "body",
"position.endNode().getProperty('name').equals('Emil')" ) ), TraverserReturnType.node ) )
.size() );
}
finally
{
transaction.finish();
}
}
@Test
public void shouldBeAbleToGetRelationshipsIfSpecified()
{
long startNode = createBasicTraversableGraph();
Transaction transaction = graph.beginTx();
List<Object> hits;
try
{
hits = serialize( actions.traverse( startNode, new HashMap<String, Object>(),
TraverserReturnType.relationship ) );
}
finally
{
transaction.finish();
}
for ( Object hit : hits )
{
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) hit;
RelationshipRepresentationTest.verifySerialisation( map );
}
}
@Test
public void shouldBeAbleToGetPathsIfSpecified()
{
long startNode = createBasicTraversableGraph();
Transaction transaction = graph.beginTx();
List<Object> hits;
try
{
hits = serialize( actions.traverse( startNode, new HashMap<String, Object>(),
TraverserReturnType.path ) );
}
finally
{
transaction.finish();
}
for ( Object hit : hits )
{
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) hit;
assertThat( map, hasKey( "start" ) );
assertThat( map, hasKey( "end" ) );
assertThat( map, hasKey( "length" ) );
}
}
@Test
public void shouldBeAbleToGetFullPathsIfSpecified()
{
long startNode = createBasicTraversableGraph();
Transaction transaction = graph.beginTx();
List<Object> hits;
try
{
hits = serialize( actions.traverse( startNode, new HashMap<String, Object>(),
TraverserReturnType.fullpath ) );
}
finally
{
transaction.finish();
}
for ( Object hit : hits )
{
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) hit;
@SuppressWarnings("unchecked")
Collection<Object> relationships = (Collection<Object>) map.get( "relationships" );
for ( Object rel : relationships )
{
@SuppressWarnings("unchecked")
Map<String, Object> relationship = (Map<String, Object>) rel;
RelationshipRepresentationTest.verifySerialisation( relationship );
}
@SuppressWarnings("unchecked")
Collection<Object> nodes = (Collection<Object>) map.get( "nodes" );
for ( Object n : nodes )
{
@SuppressWarnings("unchecked")
Map<String, Object> node = (Map<String, Object>) n;
NodeRepresentationTest.verifySerialisation( node );
}
assertThat( map, hasKey( "start" ) );
assertThat( map, hasKey( "end" ) );
assertThat( map, hasKey( "length" ) );
}
}
@Test
public void shouldBeAbleToGetShortestPaths() throws Exception
{
long[] nodes = createMoreComplexGraph();
// /paths
Transaction transaction = graph.beginTx();
try
{
List<Object> result = serialize( actions.findPaths(
nodes[0],
nodes[1],
MapUtil.map( "max_depth", 2, "algorithm", "shortestPath", "relationships",
MapUtil.map( "type", "to", "direction", "out" ) ) ) );
assertPaths( 2, nodes, 2, result );
// /path
Map<String, Object> path = serialize( actions.findSinglePath(
nodes[0],
nodes[1],
MapUtil.map( "max_depth", 2, "algorithm", "shortestPath", "relationships",
MapUtil.map( "type", "to", "direction", "out" ) ) ) );
assertPaths( 1, nodes, 2, Arrays.<Object>asList( path ) );
// /path {single: false} (has no effect)
path = serialize( actions.findSinglePath(
nodes[0],
nodes[1],
MapUtil.map( "max_depth", 2, "algorithm", "shortestPath", "relationships",
MapUtil.map( "type", "to", "direction", "out" ), "single", false ) ) );
assertPaths( 1, nodes, 2, Arrays.<Object>asList( path ) );
}
finally
{
transaction.finish();
}
}
@Test
public void shouldBeAbleToGetPathsUsingDijkstra() throws Exception
{
long[] nodes = createDijkstraGraph( true );
Transaction transaction = graph.beginTx();
try
{
// /paths
assertPaths( 1, nodes, 6, serialize( actions.findPaths(
nodes[0],
nodes[1],
map( "algorithm", "dijkstra", "cost_property", "cost", "relationships",
map( "type", "to", "direction", "out" ) ) ) ) );
// /path
Map<String, Object> path = serialize( actions.findSinglePath(
nodes[0],
nodes[1],
map( "algorithm", "dijkstra", "cost_property", "cost", "relationships",
map( "type", "to", "direction", "out" ) ) ) );
assertPaths( 1, nodes, 6, Arrays.<Object>asList( path ) );
assertEquals( 6.0d, path.get( "weight" ) );
}
finally
{
transaction.finish();
}
}
@Test
public void shouldBeAbleToGetPathsUsingDijkstraWithDefaults() throws Exception
{
long[] nodes = createDijkstraGraph( false );
// /paths
Transaction transaction = graph.beginTx();
try
{
List<Object> result = serialize( actions.findPaths(
nodes[0],
nodes[1],
map( "algorithm", "dijkstra", "cost_property", "cost", "default_cost", 1, "relationships",
map( "type", "to", "direction", "out" ) ) ) );
assertPaths( 1, nodes, 6, result );
// /path
Map<String, Object> path = serialize( actions.findSinglePath(
nodes[0],
nodes[1],
map( "algorithm", "dijkstra", "cost_property", "cost", "default_cost", 1, "relationships",
map( "type", "to", "direction", "out" ) ) ) );
assertPaths( 1, nodes, 6, Arrays.<Object>asList( path ) );
assertEquals( 6.0d, path.get( "weight" ) );
}
finally
{
transaction.finish();
}
}
@Test(expected = NotFoundException.class)
public void shouldHandleNoFoundPathsCorrectly()
{
long[] nodes = createMoreComplexGraph();
actions.findSinglePath(
nodes[0],
nodes[1],
map( "max_depth", 2, "algorithm", "shortestPath", "relationships",
map( "type", "to", "direction", "in" ), "single", false ) );
}
@Test
public void shouldAddLabelToNode() throws Exception
{
// GIVEN
long node = actions.createNode( null ).getId();
Collection<String> labels = new ArrayList<String>();
String labelName = "Wonk";
labels.add( labelName );
// WHEN
actions.addLabelToNode( node, labels );
// THEN
Transaction transaction = graph.beginTx();
try
{
Iterable<String> result = graphdbHelper.getNodeLabels( node );
assertEquals( labelName, single( result ) );
}
finally
{
transaction.finish();
}
}
@Test
public void shouldRemoveLabelFromNode() throws Exception
{
// GIVEN
String labelName = "mylabel";
long node = actions.createNode( null, label( labelName ) ).getId();
// WHEN
actions.removeLabelFromNode( node, labelName );
// THEN
assertEquals( 0, graphdbHelper.getLabelCount( node ) );
}
@Test
public void shouldListExistingLabelsOnNode() throws Exception
{
// GIVEN
long node = graphdbHelper.createNode();
String labelName1 = "LabelOne", labelName2 = "labelTwo";
graphdbHelper.addLabelToNode( node, labelName1 );
graphdbHelper.addLabelToNode( node, labelName2 );
// WHEN
Transaction transaction = graph.beginTx();
List<String> labels;
try
{
labels = (List) serialize( actions.getNodeLabels( node ) );
}
finally
{
transaction.finish();
}
// THEN
assertEquals(
asSet( labelName1, labelName2 ),
asSet( labels ) );
}
@Test
public void getNodesWithLabel() throws Exception
{
// GIVEN
String label1 = "first", label2 = "second";
long node1 = graphdbHelper.createNode( label( label1 ) );
long node2 = graphdbHelper.createNode( label( label1 ), label( label2 ) );
graphdbHelper.createNode( label( label2 ) );
// WHEN
Transaction transaction = graph.beginTx();
List<Object> representation;
try
{
representation = serialize( actions.getNodesWithLabel( label1, map() ) );
}
finally
{
transaction.finish();
}
// THEN
assertEquals( asSet( node1, node2 ), asSet( Iterables.map( new Function<Object, Long>()
{
@Override
public Long apply( Object from )
{
Map<?, ?> nodeMap = (Map<?, ?>) from;
return nodeUriToId( (String) nodeMap.get( "self" ) );
}
}, representation ) ) );
}
@Test(expected =/*THEN*/IllegalArgumentException.class)
public void getNodesWithLabelAndSeveralPropertiesShouldFail() throws Exception
{
// WHEN
actions.getNodesWithLabel( "Person", map( "name", "bob", "age", 12 ) );
}
private void assertPaths( int numPaths, long[] nodes, int length, List<Object> result )
{
assertEquals( numPaths, result.size() );
for ( Object path : result )
{
@SuppressWarnings("unchecked")
Map<String, Object> serialized = (Map<String, Object>) path;
assertTrue( serialized.get( "start" )
.toString()
.endsWith( "/" + nodes[0] ) );
assertTrue( serialized.get( "end" )
.toString()
.endsWith( "/" + nodes[1] ) );
assertEquals( length, serialized.get( "length" ) );
}
}
@Test
public void shouldCreateSchemaIndex() throws Exception
{
// GIVEN
String labelName = "person", propertyKey = "name";
// WHEN
actions.createSchemaIndex( labelName, Arrays.asList( propertyKey ) );
// THEN
Transaction transaction = graph.beginTx();
try
{
Iterable<IndexDefinition> defs = graphdbHelper.getSchemaIndexes( labelName );
assertEquals( 1, count( defs ) );
assertEquals( propertyKey, first( first( defs ).getPropertyKeys() ) );
}
finally
{
transaction.finish();
}
}
@Test
public void shouldDropSchemaIndex() throws Exception
{
// GIVEN
String labelName = "user", propertyKey = "login";
IndexDefinition index = graphdbHelper.createSchemaIndex( labelName, propertyKey );
// WHEN
actions.dropSchemaIndex( labelName, propertyKey );
// THEN
Transaction transaction = graph.beginTx();
try
{
assertFalse( "Index should have been dropped", asSet( graphdbHelper.getSchemaIndexes( labelName ) )
.contains( index ) );
}
finally
{
transaction.finish();
}
}
@Test
public void shouldGetSchemaIndexes() throws Exception
{
// GIVEN
String labelName = "mylabel", propertyKey = "name";
graphdbHelper.createSchemaIndex( labelName, propertyKey );
// WHEN
Transaction transaction = graph.beginTx();
List<Object> serialized;
try
{
serialized = serialize( actions.getSchemaIndexes( labelName ) );
}
finally
{
transaction.finish();
}
// THEN
assertEquals( 1, serialized.size() );
Map<?, ?> definition = (Map<?, ?>) serialized.get( 0 );
assertEquals( labelName, definition.get( "label" ) );
assertEquals( asList( propertyKey ), definition.get( "property_keys" ) );
}
@Test
public void shouldCreatePropertyUniquenessConstraint() throws Exception
{
// GIVEN
String labelName = "person", propertyKey = "name";
// WHEN
actions.createPropertyUniquenessConstraint( labelName, asList( propertyKey ) );
// THEN
Transaction tx = graph.beginTx();
try
{
Iterable<ConstraintDefinition> defs = graphdbHelper.getPropertyUniquenessConstraints( labelName, propertyKey );
assertEquals( asSet( propertyKey ), asSet( single( defs ).getPropertyKeys() ) );
tx.success();
}
finally
{
tx.finish();
}
}
@Test
public void shouldDropPropertyUniquenessConstraint() throws Exception
{
// GIVEN
String labelName = "user", propertyKey = "login";
ConstraintDefinition index = graphdbHelper.createPropertyUniquenessConstraint( labelName,
asList( propertyKey ) );
// WHEN
actions.dropPropertyUniquenessConstraint( labelName, asList( propertyKey ) );
// THEN
assertFalse( "Constraint should have been dropped",
asSet( graphdbHelper.getPropertyUniquenessConstraints( labelName, propertyKey ) ).contains( index ) );
}
@Test
public void shouldGetPropertyUniquenessConstraint() throws Exception
{
// GIVEN
String labelName = "mylabel", propertyKey = "name";
graphdbHelper.createPropertyUniquenessConstraint( labelName, asList( propertyKey ) );
// WHEN
Transaction transaction = graph.beginTx();
List<Object> serialized;
try
{
serialized = serialize( actions.getPropertyUniquenessConstraint( labelName, asList( propertyKey ) ) );
}
finally
{
transaction.finish();
}
// THEN
assertEquals( 1, serialized.size() );
Map<?, ?> definition = (Map<?, ?>) serialized.get( 0 );
assertEquals( labelName, definition.get( "label" ) );
assertEquals( asList( propertyKey ), definition.get( "property_keys" ) );
assertEquals( "UNIQUENESS", definition.get( "type" ) );
}
@Test
public void shouldIndexNodeOnlyOnce() throws Exception
{
long nodeId = graphdbHelper.createNode();
graphdbHelper.createRelationshipIndex( "myIndex" );
try ( Transaction tx = graph.beginTx() )
{
Pair<IndexedEntityRepresentation, Boolean> result = actions.getOrCreateIndexedNode( "myIndex",
"foo", "bar", nodeId, null );
assertThat( result.other(), is(true) );
assertThat( serialize( actions.getIndexedNodes( "myIndex", "foo", "bar" ) ).size(), is( 1 ) );
assertThat( actions.nodeIsIndexed( "myIndex", "foo", "bar", nodeId ), is(true) );
tx.success();
}
try ( Transaction tx = graph.beginTx() )
{
Pair<IndexedEntityRepresentation, Boolean> result = actions.getOrCreateIndexedNode( "myIndex",
"foo", "bar", nodeId, null );
assertThat( result.other(), is(false) );
assertThat( serialize( actions.getIndexedNodes( "myIndex", "foo", "bar" ) ).size(), is( 1 ) );
assertThat( actions.nodeIsIndexed( "myIndex", "foo", "bar", nodeId ), is(true) );
tx.success();
}
}
@Test
public void shouldIndexRelationshipOnlyOnce() throws Exception
{
long relationshipId = graphdbHelper.createRelationship( "FOO" );
graphdbHelper.createRelationshipIndex( "myIndex" );
try ( Transaction tx = graph.beginTx() )
{
Pair<IndexedEntityRepresentation, Boolean> result = actions.getOrCreateIndexedRelationship( "myIndex",
"foo", "bar", relationshipId, null, null, null, null );
assertThat( result.other(), is(true) );
assertThat( serialize( actions.getIndexedRelationships( "myIndex", "foo", "bar" ) ).size(), is( 1 ) );
assertThat( actions.relationshipIsIndexed( "myIndex", "foo", "bar", relationshipId ), is(true) );
tx.success();
}
try ( Transaction tx = graph.beginTx() )
{
Pair<IndexedEntityRepresentation, Boolean> result = actions.getOrCreateIndexedRelationship( "myIndex",
"foo", "bar", relationshipId, null, null, null, null );
assertThat( result.other(), is(false) );
assertThat( serialize( actions.getIndexedRelationships( "myIndex", "foo", "bar" ) ).size(), is( 1 ) );
assertThat( actions.relationshipIsIndexed( "myIndex", "foo", "bar", relationshipId ), is(true) );
tx.success();
}
}
@Test
public void shouldNotIndexNodeWhenAnotherNodeAlreadyIndexed() throws Exception
{
graphdbHelper.createRelationshipIndex( "myIndex" );
try ( Transaction tx = graph.beginTx() )
{
long nodeId = graphdbHelper.createNode();
Pair<IndexedEntityRepresentation, Boolean> result = actions.getOrCreateIndexedNode( "myIndex",
"foo", "bar", nodeId, null );
assertThat( result.other(), is(true) );
assertThat( serialize( actions.getIndexedNodes( "myIndex", "foo", "bar" ) ).size(), is( 1 ) );
assertThat( actions.nodeIsIndexed( "myIndex", "foo", "bar", nodeId ), is(true) );
tx.success();
}
try ( Transaction tx = graph.beginTx() )
{
long nodeId = graphdbHelper.createNode();
Pair<IndexedEntityRepresentation, Boolean> result = actions.getOrCreateIndexedNode( "myIndex",
"foo", "bar", nodeId, null );
assertThat( result.other(), is(false) );
assertThat( serialize( actions.getIndexedNodes( "myIndex", "foo", "bar" ) ).size(), is( 1 ) );
assertThat( actions.nodeIsIndexed( "myIndex", "foo", "bar", nodeId ), is(false) );
tx.success();
}
}
@Test
public void shouldNotIndexRelationshipWhenAnotherRelationshipAlreadyIndexed() throws Exception
{
graphdbHelper.createRelationshipIndex( "myIndex" );
try ( Transaction tx = graph.beginTx() )
{
long relationshipId = graphdbHelper.createRelationship( "FOO" );
Pair<IndexedEntityRepresentation, Boolean> result = actions.getOrCreateIndexedRelationship( "myIndex",
"foo", "bar", relationshipId, null, null, null, null );
assertThat( result.other(), is(true) );
assertThat( serialize( actions.getIndexedRelationships( "myIndex", "foo", "bar" ) ).size(), is( 1 ) );
assertThat( actions.relationshipIsIndexed( "myIndex", "foo", "bar", relationshipId ), is(true) );
tx.success();
}
try ( Transaction tx = graph.beginTx() )
{
long relationshipId = graphdbHelper.createRelationship( "FOO" );
Pair<IndexedEntityRepresentation, Boolean> result = actions.getOrCreateIndexedRelationship( "myIndex",
"foo", "bar", relationshipId, null, null, null, null );
assertThat( result.other(), is(false) );
assertThat( serialize( actions.getIndexedRelationships( "myIndex", "foo", "bar" ) ).size(), is( 1 ) );
assertThat( actions.relationshipIsIndexed( "myIndex", "foo", "bar", relationshipId ), is(false) );
tx.success();
}
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_web_DatabaseActionsTest.java
|
2,699
|
private class UniqueRelationshipFactory extends UniqueFactory.UniqueRelationshipFactory
{
private final Node start, end;
private final RelationshipType type;
private final Map<String, Object> properties;
UniqueRelationshipFactory( String index, Node start, Node end, String type, Map<String, Object> properties )
{
super( graphDb, index );
this.start = start;
this.end = end;
this.type = DynamicRelationshipType.withName( type );
this.properties = properties;
}
@Override
protected Relationship create( Map<String, Object> ignored )
{
return start.createRelationshipTo( end, type );
}
@Override
protected void initialize( Relationship relationship, Map<String, Object> indexed )
{
for ( Map.Entry<String, Object> property : (properties == null ? indexed : properties).entrySet() )
{
relationship.setProperty( property.getKey(), property.getValue() );
}
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_web_DatabaseActions.java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.