Unnamed: 0
int64
0
6.7k
func
stringlengths
12
89.6k
target
bool
2 classes
project
stringlengths
45
151
2,700
private class UniqueNodeFactory extends UniqueFactory.UniqueNodeFactory { private final Map<String, Object> properties; UniqueNodeFactory( String index, Map<String, Object> properties ) { super( graphDb, index ); this.properties = properties; } @Override protected void initialize( Node node, Map<String, Object> indexed ) { for ( Map.Entry<String, Object> property : (properties == null ? indexed : properties).entrySet() ) { node.setProperty( property.getKey(), property.getValue() ); } } }
false
community_server_src_main_java_org_neo4j_server_rest_web_DatabaseActions.java
2,701
public static class Provider extends InjectableProvider<DatabaseActions> { private final DatabaseActions database; public Provider( DatabaseActions database ) { super( DatabaseActions.class ); this.database = database; } @Override public DatabaseActions getValue( HttpContext c ) { return database; } }
false
community_server_src_main_java_org_neo4j_server_rest_web_DatabaseActions.java
2,702
NONE { @Override Representation getRepresentationFor( Representation delegate, float score ) { return delegate; } @Override QueryContext updateQueryContext( QueryContext original ) { return original; } };
false
community_server_src_main_java_org_neo4j_server_rest_web_DatabaseActions.java
2,703
SCORE_ORDER { @Override QueryContext updateQueryContext( QueryContext original ) { return original.sortByScore(); } },
false
community_server_src_main_java_org_neo4j_server_rest_web_DatabaseActions.java
2,704
}, RELEVANCE_ORDER { @Override QueryContext updateQueryContext( QueryContext original ) { return original.sort( Sort.RELEVANCE ); } },
false
community_server_src_main_java_org_neo4j_server_rest_web_DatabaseActions.java
2,705
INDEX_ORDER { @Override QueryContext updateQueryContext( QueryContext original ) { return original.sort( Sort.INDEXORDER ); } }, RELEVANCE_ORDER
false
community_server_src_main_java_org_neo4j_server_rest_web_DatabaseActions.java
2,706
private class FindParams { private final long startId; private final long endId; private final Map<String, Object> map; private Node startNode; private Node endNode; private PathFinder<? extends Path> finder; @SuppressWarnings("rawtypes") private PathRepresentationCreator representationCreator = PATH_REPRESENTATION_CREATOR; public FindParams( final long startId, final long endId, final Map<String, Object> map ) { this.startId = startId; this.endId = endId; this.map = map; } public Node getStartNode() { return startNode; } public Node getEndNode() { return endNode; } public PathFinder<? extends Path> getFinder() { return finder; } @SuppressWarnings("unchecked") public PathRepresentation<? extends Path> pathRepresentationOf( Path path ) { return representationCreator.from( path ); } public FindParams invoke() { startNode = graphDb.getNodeById( startId ); endNode = graphDb.getNodeById( endId ); Integer maxDepthObj = (Integer) map.get( "max_depth" ); int maxDepth = (maxDepthObj != null) ? maxDepthObj : 1; RelationshipExpander expander = RelationshipExpanderBuilder.describeRelationships( map ); String algorithm = (String) map.get( "algorithm" ); algorithm = (algorithm != null) ? algorithm : "shortestPath"; finder = getAlgorithm( algorithm, expander, maxDepth ); return this; } private PathFinder<? extends Path> getAlgorithm( String algorithm, RelationshipExpander expander, int maxDepth ) { if ( algorithm.equals( "shortestPath" ) ) { return GraphAlgoFactory.shortestPath( expander, maxDepth ); } else if ( algorithm.equals( "allSimplePaths" ) ) { return GraphAlgoFactory.allSimplePaths( expander, maxDepth ); } else if ( algorithm.equals( "allPaths" ) ) { return GraphAlgoFactory.allPaths( expander, maxDepth ); } else if ( algorithm.equals( "dijkstra" ) ) { String costProperty = (String) map.get( "cost_property" ); Number defaultCost = (Number) map.get( "default_cost" ); CostEvaluator<Double> costEvaluator = defaultCost == null ? CommonEvaluators.doubleCostEvaluator( costProperty ) : CommonEvaluators.doubleCostEvaluator( costProperty, defaultCost.doubleValue() ); representationCreator = WEIGHTED_PATH_REPRESENTATION_CREATOR; return GraphAlgoFactory.dijkstra( expander, costEvaluator ); } throw new RuntimeException( "Failed to find matching algorithm" ); } }
false
community_server_src_main_java_org_neo4j_server_rest_web_DatabaseActions.java
2,707
{ @Override protected PathRepresentation underlyingObjectToObject( Path path ) { return findParams.pathRepresentationOf( path ); } };
false
community_server_src_main_java_org_neo4j_server_rest_web_DatabaseActions.java
2,708
{ @Override protected Representation underlyingObjectToObject( Path position ) { return returnType.toRepresentation( position ); } };
false
community_server_src_main_java_org_neo4j_server_rest_web_DatabaseActions.java
2,709
{ @Override protected Representation underlyingObjectToObject( Relationship relationship ) { return new IndexedEntityRepresentation( relationship, key, value, indexRepresentation ); } };
false
community_server_src_main_java_org_neo4j_server_rest_web_DatabaseActions.java
2,710
{ @Override protected Representation underlyingObjectToObject( Relationship rel ) { final RelationshipRepresentation relationshipRepresentation = new RelationshipRepresentation( rel ); if ( order != null ) { return order.getRepresentationFor( relationshipRepresentation, result.currentScore() ); } return relationshipRepresentation; } };
false
community_server_src_main_java_org_neo4j_server_rest_web_DatabaseActions.java
2,711
{ @Override protected Representation underlyingObjectToObject( Node node ) { final NodeRepresentation nodeRepresentation = new NodeRepresentation( node ); if ( order == null ) { return nodeRepresentation; } return order.getRepresentationFor( nodeRepresentation, result.currentScore() ); } };
false
community_server_src_main_java_org_neo4j_server_rest_web_DatabaseActions.java
2,712
{ @Override protected Representation underlyingObjectToObject( Node node ) { return new IndexedEntityRepresentation( node, key, value, indexRepresentation ); } };
false
community_server_src_main_java_org_neo4j_server_rest_web_DatabaseActions.java
2,713
{ @Override protected String underlyingObjectToObject( Label object ) { return object.name(); } };
false
community_server_src_main_java_org_neo4j_server_rest_web_DatabaseActions.java
2,714
{ @Override public ValueRepresentation apply( String key ) { return ValueRepresentation.string( key ); } }, GlobalGraphOperations.at( graphDb ).getAllPropertyKeys() ) );
false
community_server_src_main_java_org_neo4j_server_rest_web_DatabaseActions.java
2,715
{ @Override public boolean accept( ConstraintDefinition item ) { return item.isConstraintType( ConstraintType.UNIQUENESS ) && propertyKeysSet.equals( asSet( item.getPropertyKeys() ) ); } };
false
community_server_src_main_java_org_neo4j_server_rest_web_DatabaseActions.java
2,716
return filter(new Predicate<ConstraintDefinition>(){ @Override public boolean accept( ConstraintDefinition item ) { return item.isConstraintType( type ); } }, graphDb.schema().getConstraints( label( labelName ) ) );
false
community_server_src_main_java_org_neo4j_server_rest_web_DatabaseActions.java
2,717
{ @Override public Long apply( Object from ) { Map<?, ?> nodeMap = (Map<?, ?>) from; return nodeUriToId( (String) nodeMap.get( "self" ) ); } }, representation ) ) );
false
community_server_src_test_java_org_neo4j_server_rest_web_DatabaseActionsTest.java
2,718
public class DatabaseMetadataServiceTest { @Test public void shouldAdvertiseRelationshipTypesThatCurrentlyExistInTheDatabase() throws Throwable { InternalAbstractGraphDatabase db = (InternalAbstractGraphDatabase)new TestGraphDatabaseFactory().newImpermanentDatabase(); Transaction tx = db.beginTx(); Node node = db.createNode(); node.createRelationshipTo( db.createNode(), withName( "a" ) ); node.createRelationshipTo( db.createNode(), withName( "b" ) ); node.createRelationshipTo( db.createNode(), withName( "c" ) ); tx.success(); tx.finish(); Database database = new WrappedDatabase( db ); DatabaseMetadataService service = new DatabaseMetadataService( database ); tx = db.beginTx(); Response response = service.getRelationshipTypes(); assertEquals( 200, response.getStatus() ); List<Map<String, Object>> jsonList = JsonHelper.jsonToList( response.getEntity() .toString() ); assertEquals( 3, jsonList.size() ); tx.finish(); database.stop(); } }
false
community_server_src_test_java_org_neo4j_server_rest_web_DatabaseMetadataServiceTest.java
2,719
{ @Override public IndexDefinitionRepresentation apply( IndexDefinition definition ) { return new IndexDefinitionRepresentation( definition ); } }, definitions );
false
community_server_src_main_java_org_neo4j_server_rest_web_DatabaseActions.java
2,720
@Path( "ext" ) public class ExtensionService { private static final String PATH_EXTENSION = "/{name}"; private static final String PATH_GRAPHDB_EXTENSION_METHOD = PATH_EXTENSION + "/graphdb/{method}"; private static final String PATH_NODE_EXTENSION_METHOD = PATH_EXTENSION + "/node/{nodeId}/{method}"; private static final String PATH_RELATIONSHIP_EXTENSION_METHOD = PATH_EXTENSION + "/relationship/{relationshipId}/{method}"; private final InputFormat input; private final OutputFormat output; private final PluginInvocator extensions; private final GraphDatabaseAPI graphDb; public ExtensionService( @Context InputFormat input, @Context OutputFormat output, @Context PluginInvocator extensions, @Context Database database ) { this.input = input; this.output = output; this.extensions = extensions; this.graphDb = database.getGraph(); } public OutputFormat getOutputFormat() { return output; } private Node node( long id ) throws NodeNotFoundException { try(Transaction tx = graphDb.beginTx()) { Node node = graphDb.getNodeById( id ); tx.success(); return node; } catch ( NotFoundException e ) { throw new NodeNotFoundException( e ); } } private Relationship relationship( long id ) throws RelationshipNotFoundException { try(Transaction tx = graphDb.beginTx()) { Relationship relationship = graphDb.getRelationshipById( id ); tx.success(); return relationship; } catch ( NotFoundException e ) { throw new RelationshipNotFoundException(); } } @GET public Response getExtensionsList() { return output.ok( this.extensionsList() ); } @GET @Path( PATH_EXTENSION ) public Response getExtensionList( @PathParam( "name" ) String name ) { try { return output.ok( this.extensionList( name ) ); } catch ( PluginLookupException e ) { return output.notFound( e ); } } @POST @Path( PATH_GRAPHDB_EXTENSION_METHOD ) public Response invokeGraphDatabaseExtension( @PathParam( "name" ) String name, @PathParam( "method" ) String method, String data ) { try { return output.ok( this.invokeGraphDatabaseExtension( name, method, input.readParameterList( data ) ) ); } catch ( BadInputException e ) { return output.badRequest( e ); } catch ( PluginLookupException e ) { return output.notFound( e ); } catch ( BadPluginInvocationException e ) { return output.badRequest( e.getCause() ); } catch ( SyntaxException e ) { return output.badRequest( e.getCause() ); } catch ( PluginInvocationFailureException e ) { return output.serverError( e.getCause() ); } catch ( Exception e ) { return output.serverError( e ); } } @GET @Path( PATH_GRAPHDB_EXTENSION_METHOD ) public Response getGraphDatabaseExtensionDescription( @PathParam( "name" ) String name, @PathParam( "method" ) String method ) { try { return output.ok( this.describeGraphDatabaseExtension( name, method ) ); } catch ( PluginLookupException e ) { return output.notFound( e ); } } @POST @Path( PATH_NODE_EXTENSION_METHOD ) public Response invokeNodeExtension( @PathParam( "name" ) String name, @PathParam( "method" ) String method, @PathParam( "nodeId" ) long nodeId, String data ) { try { return output.ok( this.invokeNodeExtension( nodeId, name, method, input.readParameterList( data ) ) ); } catch ( NodeNotFoundException e ) { return output.notFound( e ); } catch ( BadInputException e ) { return output.badRequest( e ); } catch ( PluginLookupException e ) { return output.notFound( e ); } catch ( BadPluginInvocationException e ) { return output.badRequest( e.getCause() ); } catch ( PluginInvocationFailureException e ) { return output.serverError( e.getCause() ); } catch ( Exception e ) { return output.serverError( e ); } } @GET @Path( PATH_NODE_EXTENSION_METHOD ) public Response getNodeExtensionDescription( @PathParam( "name" ) String name, @PathParam( "method" ) String method, @PathParam( "nodeId" ) long nodeId ) { try { return output.ok( this.describeNodeExtension( name, method ) ); } catch ( PluginLookupException e ) { return output.notFound( e ); } catch ( Exception e ) { return output.serverError( e ); } } @POST @Path( PATH_RELATIONSHIP_EXTENSION_METHOD ) public Response invokeRelationshipExtension( @PathParam( "name" ) String name, @PathParam( "method" ) String method, @PathParam( "relationshipId" ) long relationshipId, String data ) { try { return output.ok( this.invokeRelationshipExtension( relationshipId, name, method, input.readParameterList( data ) ) ); } catch ( RelationshipNotFoundException e ) { return output.notFound( e ); } catch ( BadInputException e ) { return output.badRequest( e ); } catch ( PluginLookupException e ) { return output.notFound( e ); } catch ( BadPluginInvocationException e ) { return output.badRequest( e.getCause() ); } catch ( PluginInvocationFailureException e ) { return output.serverError( e.getCause() ); } catch ( Exception e ) { return output.serverError( e ); } } @GET @Path( PATH_RELATIONSHIP_EXTENSION_METHOD ) public Response getRelationshipExtensionDescription( @PathParam( "name" ) String name, @PathParam( "method" ) String method, @PathParam( "relationshipId" ) long relationshipId ) { try { return output.ok( this.describeRelationshipExtension( name, method ) ); } catch ( PluginLookupException e ) { return output.notFound( e ); } catch ( Exception e ) { return output.serverError( e ); } } // Extensions protected Representation extensionsList() { return new MappingRepresentation( "extensions" ) { @Override protected void serialize( MappingSerializer serializer ) { for ( String extension : extensions.extensionNames() ) { serializer.putUri( extension, "ext/" + extension ); } } }; } protected Representation extensionList( String extensionName ) throws PluginLookupException { return new ServerExtensionRepresentation( extensionName, extensions.describeAll( extensionName ) ); } protected Representation invokeGraphDatabaseExtension( String extensionName, String method, ParameterList data ) throws PluginLookupException, BadInputException, PluginInvocationFailureException, BadPluginInvocationException { return extensions.invoke( graphDb, extensionName, GraphDatabaseService.class, method, graphDb, data ); } protected Representation describeGraphDatabaseExtension( String extensionName, String method ) throws PluginLookupException { return extensions.describe( extensionName, GraphDatabaseService.class, method ); } protected Representation invokeNodeExtension( long nodeId, String extensionName, String method, ParameterList data ) throws NodeNotFoundException, PluginLookupException, BadInputException, PluginInvocationFailureException, BadPluginInvocationException { return extensions.invoke( graphDb, extensionName, Node.class, method, node( nodeId ), data ); } protected Representation describeNodeExtension( String extensionName, String method ) throws PluginLookupException { return extensions.describe( extensionName, Node.class, method ); } protected Representation invokeRelationshipExtension( long relationshipId, String extensionName, String method, ParameterList data ) throws RelationshipNotFoundException, PluginLookupException, BadInputException, PluginInvocationFailureException, BadPluginInvocationException { return extensions.invoke( graphDb, extensionName, Relationship.class, method, relationship( relationshipId ), data ); } protected Representation describeRelationshipExtension( String extensionName, String method ) throws PluginLookupException { return extensions.describe( extensionName, Relationship.class, method ); } }
false
community_server_src_main_java_org_neo4j_server_rest_web_ExtensionService.java
2,721
@SuppressWarnings("serial") public static class AmpersandSeparatedCollection extends LinkedHashSet<String> { public AmpersandSeparatedCollection( String path ) { for ( String e : path.split( "&" ) ) { if ( e.trim() .length() > 0 ) { add( e ); } } } }
false
community_server_src_main_java_org_neo4j_server_rest_web_RestfulGraphDatabase.java
2,722
{ @Override public Pair<String, Object> apply( Map.Entry<String, List<String>> queryEntry ) { try { Object propertyValue = input.readValue( queryEntry.getValue().get( 0 ) ); if ( propertyValue instanceof Collection<?> ) { propertyValue = PropertySettingStrategy.convertToNativeArray( (Collection<?>) propertyValue ); } return Pair.of( queryEntry.getKey(), propertyValue ); } catch ( BadInputException e ) { throw new IllegalArgumentException( String.format( "Unable to deserialize property value for %s.", queryEntry.getKey() ), e ); } } };
false
community_server_src_main_java_org_neo4j_server_rest_web_RestfulGraphDatabase.java
2,723
@Path( "/" ) public class RestfulGraphDatabase { @SuppressWarnings("serial") public static class AmpersandSeparatedCollection extends LinkedHashSet<String> { public AmpersandSeparatedCollection( String path ) { for ( String e : path.split( "&" ) ) { if ( e.trim() .length() > 0 ) { add( e ); } } } } private static final String PATH_NODE = PATH_NODES + "/{nodeId}"; private static final String PATH_NODE_PROPERTIES = PATH_NODE + "/properties"; private static final String PATH_NODE_PROPERTY = PATH_NODE_PROPERTIES + "/{key}"; private static final String PATH_NODE_RELATIONSHIPS = PATH_NODE + "/relationships"; private static final String PATH_RELATIONSHIP = PATH_RELATIONSHIPS + "/{relationshipId}"; private static final String PATH_NODE_RELATIONSHIPS_W_DIR = PATH_NODE_RELATIONSHIPS + "/{direction}"; private static final String PATH_NODE_RELATIONSHIPS_W_DIR_N_TYPES = PATH_NODE_RELATIONSHIPS_W_DIR + "/{types}"; private static final String PATH_RELATIONSHIP_PROPERTIES = PATH_RELATIONSHIP + "/properties"; private static final String PATH_RELATIONSHIP_PROPERTY = PATH_RELATIONSHIP_PROPERTIES + "/{key}"; private static final String PATH_NODE_TRAVERSE = PATH_NODE + "/traverse/{returnType}"; private static final String PATH_NODE_PATH = PATH_NODE + "/path"; private static final String PATH_NODE_PATHS = PATH_NODE + "/paths"; private static final String PATH_NODE_LABELS = PATH_NODE + "/labels"; private static final String PATH_NODE_LABEL = PATH_NODE + "/labels/{label}"; private static final String PATH_PROPERTY_KEYS = "propertykeys"; protected static final String PATH_NAMED_NODE_INDEX = PATH_NODE_INDEX + "/{indexName}"; protected static final String PATH_NODE_INDEX_GET = PATH_NAMED_NODE_INDEX + "/{key}/{value}"; protected static final String PATH_NODE_INDEX_QUERY_WITH_KEY = PATH_NAMED_NODE_INDEX + "/{key}"; // // http://localhost/db/data/index/node/foo?query=somelucenestuff protected static final String PATH_NODE_INDEX_ID = PATH_NODE_INDEX_GET + "/{id}"; protected static final String PATH_NODE_INDEX_REMOVE_KEY = PATH_NAMED_NODE_INDEX + "/{key}/{id}"; protected static final String PATH_NODE_INDEX_REMOVE = PATH_NAMED_NODE_INDEX + "/{id}"; protected static final String PATH_NAMED_RELATIONSHIP_INDEX = PATH_RELATIONSHIP_INDEX + "/{indexName}"; protected static final String PATH_RELATIONSHIP_INDEX_GET = PATH_NAMED_RELATIONSHIP_INDEX + "/{key}/{value}"; protected static final String PATH_RELATIONSHIP_INDEX_QUERY_WITH_KEY = PATH_NAMED_RELATIONSHIP_INDEX + "/{key}"; protected static final String PATH_RELATIONSHIP_INDEX_ID = PATH_RELATIONSHIP_INDEX_GET + "/{id}"; protected static final String PATH_RELATIONSHIP_INDEX_REMOVE_KEY = PATH_NAMED_RELATIONSHIP_INDEX + "/{key}/{id}"; protected static final String PATH_RELATIONSHIP_INDEX_REMOVE = PATH_NAMED_RELATIONSHIP_INDEX + "/{id}"; public static final String PATH_AUTO_INDEX = "index/auto/{type}"; protected static final String PATH_AUTO_INDEX_STATUS = PATH_AUTO_INDEX + "/status"; protected static final String PATH_AUTO_INDEXED_PROPERTIES = PATH_AUTO_INDEX + "/properties"; protected static final String PATH_AUTO_INDEX_PROPERTY_DELETE = PATH_AUTO_INDEXED_PROPERTIES + "/{property}"; protected static final String PATH_AUTO_INDEX_GET = PATH_AUTO_INDEX + "/{key}/{value}"; public static final String PATH_ALL_NODES_LABELED = "label/{label}/nodes"; public static final String PATH_SCHEMA_INDEX_LABEL = PATH_SCHEMA_INDEX + "/{label}"; public static final String PATH_SCHEMA_INDEX_LABEL_PROPERTY = PATH_SCHEMA_INDEX_LABEL + "/{property}"; public static final String PATH_SCHEMA_CONSTRAINT_LABEL = PATH_SCHEMA_CONSTRAINT + "/{label}"; public static final String PATH_SCHEMA_CONSTRAINT_LABEL_UNIQUENESS = PATH_SCHEMA_CONSTRAINT_LABEL + "/uniqueness"; public static final String PATH_SCHEMA_CONSTRAINT_LABEL_UNIQUENESS_PROPERTY = PATH_SCHEMA_CONSTRAINT_LABEL_UNIQUENESS + "/{property}"; public static final String NODE_AUTO_INDEX_TYPE = "node"; public static final String RELATIONSHIP_AUTO_INDEX_TYPE = "relationship"; private static final String SIXTY_SECONDS = "60"; private static final String FIFTY_ENTRIES = "50"; private static final String UNIQUENESS_MODE_GET_OR_CREATE = "get_or_create"; private static final String UNIQUENESS_MODE_CREATE_OR_FAIL = "create_or_fail"; // TODO Obviously change name/content on this private static final String HEADER_TRANSACTION = "Transaction"; private final DatabaseActions actions; private final OutputFormat output; private final InputFormat input; public static final String PATH_TO_CREATE_PAGED_TRAVERSERS = PATH_NODE + "/paged/traverse/{returnType}"; public static final String PATH_TO_PAGED_TRAVERSERS = PATH_NODE + "/paged/traverse/{returnType}/{traverserId}"; private enum UniqueIndexType { None, GetOrCreate, CreateOrFail } public RestfulGraphDatabase( @Context InputFormat input, @Context OutputFormat output, @Context DatabaseActions actions ) { this.input = input; this.output = output; this.actions = actions; } public OutputFormat getOutputFormat() { return output; } private Response nothing() { return output.noContent(); } private Long extractNodeIdOrNull( String uri ) throws BadInputException { if ( uri == null ) { return null; } return extractNodeId( uri ); } private long extractNodeId( String uri ) throws BadInputException { try { return Long.parseLong( uri.substring( uri.lastIndexOf( "/" ) + 1 ) ); } catch ( NumberFormatException | NullPointerException ex ) { throw new BadInputException( ex ); } } private Long extractRelationshipIdOrNull( String uri ) throws BadInputException { if ( uri == null ) { return null; } return extractRelationshipId( uri ); } private long extractRelationshipId( String uri ) throws BadInputException { return extractNodeId( uri ); } @GET public Response getRoot() { return output.ok( actions.root() ); } // Nodes @POST @Path(PATH_NODES) public Response createNode( @HeaderParam(HEADER_TRANSACTION) ForceMode force, String body ) { try { return output.created( actions( force ).createNode( input.readMap( body ) ) ); } catch ( ArrayStoreException ase ) { return generateBadRequestDueToMangledJsonResponse( body ); } catch ( BadInputException e ) { return output.badRequest( e ); } catch ( ClassCastException e ) { return output.badRequest( e ); } } private Response generateBadRequestDueToMangledJsonResponse( String body ) { return output.badRequest( MediaType.TEXT_PLAIN_TYPE, "Invalid JSON array in POST body: " + body ); } @GET @Path(PATH_NODE) public Response getNode( @PathParam("nodeId") long nodeId ) { try { return output.ok( actions.getNode( nodeId ) ); } catch ( NodeNotFoundException e ) { return output.notFound( e ); } } @DELETE @Path(PATH_NODE) public Response deleteNode( @HeaderParam(HEADER_TRANSACTION) ForceMode force, @PathParam("nodeId") long nodeId ) { try { actions( force ).deleteNode( nodeId ); return nothing(); } catch ( NodeNotFoundException e ) { return output.notFound( e ); } catch ( OperationFailureException e ) { return output.conflict( e ); } } // Node properties @PUT @Path(PATH_NODE_PROPERTIES) public Response setAllNodeProperties( @HeaderParam(HEADER_TRANSACTION) ForceMode force, @PathParam("nodeId") long nodeId, String body ) { try { actions( force ).setAllNodeProperties( nodeId, input.readMap( body ) ); } catch ( BadInputException e ) { return output.badRequest( e ); } catch ( ArrayStoreException ase ) { return generateBadRequestDueToMangledJsonResponse( body ); } catch ( NodeNotFoundException e ) { return output.notFound( e ); } catch ( ConstraintViolationException e ) { return output.conflict( e ); } return nothing(); } @GET @Path(PATH_NODE_PROPERTIES) public Response getAllNodeProperties( @PathParam("nodeId") long nodeId ) { final PropertiesRepresentation properties; try { properties = actions.getAllNodeProperties( nodeId ); } catch ( NodeNotFoundException e ) { return output.notFound( e ); } if ( properties.isEmpty() ) { return nothing(); } return output.ok( properties ); } @PUT @Path(PATH_NODE_PROPERTY) public Response setNodeProperty( @HeaderParam(HEADER_TRANSACTION) ForceMode force, @PathParam("nodeId") long nodeId, @PathParam("key") String key, String body ) { try { actions( force ).setNodeProperty( nodeId, key, input.readValue( body ) ); } catch ( BadInputException e ) { return output.badRequest( e ); } catch ( ArrayStoreException ase ) { return generateBadRequestDueToMangledJsonResponse( body ); } catch ( NodeNotFoundException e ) { return output.notFound( e ); } catch ( ConstraintViolationException e) { return output.conflict( e ); } return nothing(); } @GET @Path(PATH_NODE_PROPERTY) public Response getNodeProperty( @HeaderParam(HEADER_TRANSACTION) ForceMode force, @PathParam("nodeId") long nodeId, @PathParam("key") String key ) { try { Representation representation = actions( force ).getNodeProperty( nodeId, key ); return output.ok( representation ); } catch ( NodeNotFoundException e ) { return output.notFound( e ); } catch ( NoSuchPropertyException e ) { return output.notFound( e ); } } @DELETE @Path(PATH_NODE_PROPERTY) public Response deleteNodeProperty( @HeaderParam(HEADER_TRANSACTION) ForceMode force, @PathParam("nodeId") long nodeId, @PathParam("key") String key ) { try { actions( force ).removeNodeProperty( nodeId, key ); } catch ( NodeNotFoundException e ) { return output.notFound( e ); } catch ( NoSuchPropertyException e ) { return output.notFound( e ); } return nothing(); } @DELETE @Path(PATH_NODE_PROPERTIES) public Response deleteAllNodeProperties( @HeaderParam(HEADER_TRANSACTION) ForceMode force, @PathParam("nodeId") long nodeId ) { try { actions( force ).removeAllNodeProperties( nodeId ); } catch ( NodeNotFoundException e ) { return output.notFound( e ); } catch ( PropertyValueException e ) { return output.badRequest( e ); } return nothing(); } // Node Labels @POST @Path( PATH_NODE_LABELS ) public Response addNodeLabel( @HeaderParam( HEADER_TRANSACTION ) ForceMode force, @PathParam( "nodeId" ) long nodeId, String body ) { try { Object rawInput = input.readValue( body ); if ( rawInput instanceof String ) { ArrayList<String> s = new ArrayList<>(); s.add((String) rawInput); actions( force ).addLabelToNode( nodeId, s ); } else if(rawInput instanceof Collection) { actions( force ).addLabelToNode( nodeId, (Collection<String>) rawInput ); } else { throw new BadInputException( format( "Label name must be a string. Got: '%s'", rawInput ) ); } } catch ( BadInputException e ) { return output.badRequest( e ); } catch ( ArrayStoreException ase ) { return generateBadRequestDueToMangledJsonResponse( body ); } catch ( NodeNotFoundException e ) { return output.notFound( e ); } return nothing(); } @PUT @Path( PATH_NODE_LABELS ) public Response setNodeLabels( @HeaderParam( HEADER_TRANSACTION ) ForceMode force, @PathParam( "nodeId" ) long nodeId, String body ) { try { Object rawInput = input.readValue( body ); if ( !(rawInput instanceof Collection) ) { throw new BadInputException( format( "Input must be an array of Strings. Got: '%s'", rawInput ) ); } else { actions( force ).setLabelsOnNode( nodeId, (Collection<String>) rawInput ); } } catch ( BadInputException e ) { return output.badRequest( e ); } catch ( ArrayStoreException ase ) { return generateBadRequestDueToMangledJsonResponse( body ); } catch ( NodeNotFoundException e ) { return output.notFound( e ); } return nothing(); } @DELETE @Path( PATH_NODE_LABEL ) public Response removeNodeLabel( @HeaderParam( HEADER_TRANSACTION ) ForceMode force, @PathParam( "nodeId" ) long nodeId, @PathParam( "label" ) String labelName ) { try { actions( force ).removeLabelFromNode( nodeId, labelName ); } catch ( NodeNotFoundException e ) { return output.notFound( e ); } return nothing(); } @GET @Path( PATH_NODE_LABELS ) public Response getNodeLabels( @HeaderParam( HEADER_TRANSACTION ) ForceMode force, @PathParam( "nodeId" ) long nodeId ) { try { return output.ok( actions( force ).getNodeLabels( nodeId ) ); } catch ( NodeNotFoundException e ) { return output.notFound( e ); } } @GET @Path( PATH_ALL_NODES_LABELED ) public Response getNodesWithLabelAndProperty( @PathParam("label") String labelName, @Context UriInfo uriInfo ) { try { if ( labelName.isEmpty() ) throw new BadInputException( "Empty label name" ); Map<String, Object> properties = toMap( map( queryParamsToProperties, uriInfo.getQueryParameters().entrySet())); return output.ok( actions.getNodesWithLabel( labelName, properties ) ); } catch ( BadInputException e ) { return output.badRequest( e ); } } @GET @Path( PATH_LABELS ) public Response getAllLabels( ) { return output.ok( actions.getAllLabels() ); } // Property keys @GET @Path( PATH_PROPERTY_KEYS ) public Response getAllPropertyKeys( ) { return output.ok( actions.getAllPropertyKeys() ); } // Relationships @SuppressWarnings("unchecked") @POST @Path(PATH_NODE_RELATIONSHIPS) public Response createRelationship( @HeaderParam(HEADER_TRANSACTION) ForceMode force, @PathParam("nodeId") long startNodeId, String body ) { final Map<String, Object> data; final long endNodeId; final String type; final Map<String, Object> properties; try { data = input.readMap( body ); endNodeId = extractNodeId( (String) data.get( "to" ) ); type = (String) data.get( "type" ); properties = (Map<String, Object>) data.get( "data" ); } catch ( BadInputException e ) { return output.badRequest( e ); } catch ( ClassCastException e ) { return output.badRequest( e ); } try { return output.created( actions( force ).createRelationship( startNodeId, endNodeId, type, properties ) ); } catch ( StartNodeNotFoundException e ) { return output.notFound( e ); } catch ( EndNodeNotFoundException e ) { return output.badRequest( e ); } catch ( PropertyValueException e ) { return output.badRequest( e ); } catch ( BadInputException e ) { return output.badRequest( e ); } } @GET @Path(PATH_RELATIONSHIP) public Response getRelationship( @PathParam("relationshipId") long relationshipId ) { try { return output.ok( actions.getRelationship( relationshipId ) ); } catch ( RelationshipNotFoundException e ) { return output.notFound( e ); } } @DELETE @Path(PATH_RELATIONSHIP) public Response deleteRelationship( @HeaderParam(HEADER_TRANSACTION) ForceMode force, @PathParam("relationshipId") long relationshipId ) { try { actions( force ).deleteRelationship( relationshipId ); } catch ( RelationshipNotFoundException e ) { return output.notFound( e ); } return nothing(); } @GET @Path(PATH_NODE_RELATIONSHIPS_W_DIR) public Response getNodeRelationships( @PathParam("nodeId") long nodeId, @PathParam("direction") RelationshipDirection direction ) { try { return output.ok( actions.getNodeRelationships( nodeId, direction, Collections.<String>emptyList() ) ); } catch ( NodeNotFoundException e ) { return output.notFound( e ); } } @GET @Path(PATH_NODE_RELATIONSHIPS_W_DIR_N_TYPES) public Response getNodeRelationships( @PathParam("nodeId") long nodeId, @PathParam("direction") RelationshipDirection direction, @PathParam("types") AmpersandSeparatedCollection types ) { try { return output.ok( actions.getNodeRelationships( nodeId, direction, types ) ); } catch ( NodeNotFoundException e ) { return output.notFound( e ); } } // Relationship properties @GET @Path(PATH_RELATIONSHIP_PROPERTIES) public Response getAllRelationshipProperties( @PathParam("relationshipId") long relationshipId ) { final PropertiesRepresentation properties; try { properties = actions.getAllRelationshipProperties( relationshipId ); } catch ( RelationshipNotFoundException e ) { return output.notFound( e ); } if ( properties.isEmpty() ) { return nothing(); } else { return output.ok( properties ); } } @GET @Path(PATH_RELATIONSHIP_PROPERTY) public Response getRelationshipProperty( @PathParam("relationshipId") long relationshipId, @PathParam("key") String key ) { try { return output.ok( actions.getRelationshipProperty( relationshipId, key ) ); } catch ( RelationshipNotFoundException e ) { return output.notFound( e ); } catch ( NoSuchPropertyException e ) { return output.notFound( e ); } } @PUT @Path(PATH_RELATIONSHIP_PROPERTIES) @Consumes(MediaType.APPLICATION_JSON) public Response setAllRelationshipProperties( @HeaderParam(HEADER_TRANSACTION) ForceMode force, @PathParam("relationshipId") long relationshipId, String body ) { try { actions( force ).setAllRelationshipProperties( relationshipId, input.readMap( body ) ); } catch ( BadInputException e ) { return output.badRequest( e ); } catch ( RelationshipNotFoundException e ) { return output.notFound( e ); } return nothing(); } @PUT @Path(PATH_RELATIONSHIP_PROPERTY) @Consumes(MediaType.APPLICATION_JSON) public Response setRelationshipProperty( @HeaderParam(HEADER_TRANSACTION) ForceMode force, @PathParam("relationshipId") long relationshipId, @PathParam("key") String key, String body ) { try { actions( force ).setRelationshipProperty( relationshipId, key, input.readValue( body ) ); } catch ( BadInputException e ) { return output.badRequest( e ); } catch ( RelationshipNotFoundException e ) { return output.notFound( e ); } return nothing(); } @DELETE @Path(PATH_RELATIONSHIP_PROPERTIES) public Response deleteAllRelationshipProperties( @HeaderParam(HEADER_TRANSACTION) ForceMode force, @PathParam("relationshipId") long relationshipId ) { try { actions( force ).removeAllRelationshipProperties( relationshipId ); } catch ( RelationshipNotFoundException e ) { return output.notFound( e ); } catch ( PropertyValueException e ) { return output.badRequest( e ); } return nothing(); } @DELETE @Path(PATH_RELATIONSHIP_PROPERTY) public Response deleteRelationshipProperty( @HeaderParam(HEADER_TRANSACTION) ForceMode force, @PathParam("relationshipId") long relationshipId, @PathParam("key") String key ) { try { actions( force ).removeRelationshipProperty( relationshipId, key ); } catch ( RelationshipNotFoundException e ) { return output.notFound( e ); } catch ( NoSuchPropertyException e ) { return output.notFound( e ); } return nothing(); } // Index @GET @Path(PATH_NODE_INDEX) public Response getNodeIndexRoot() { if ( actions.getNodeIndexNames().length == 0 ) { return output.noContent(); } return output.ok( actions.nodeIndexRoot() ); } @POST @Path(PATH_NODE_INDEX) @Consumes(MediaType.APPLICATION_JSON) public Response jsonCreateNodeIndex( @HeaderParam(HEADER_TRANSACTION) ForceMode force, String json ) { try { return output.created( actions( force ).createNodeIndex( input.readMap( json ) ) ); } catch ( IllegalArgumentException e ) { return output.badRequest( e ); } catch ( BadInputException e ) { return output.badRequest( e ); } } @GET @Path(PATH_RELATIONSHIP_INDEX) public Response getRelationshipIndexRoot() { if ( actions.getRelationshipIndexNames().length == 0 ) { return output.noContent(); } return output.ok( actions.relationshipIndexRoot() ); } @POST @Path(PATH_RELATIONSHIP_INDEX) @Consumes(MediaType.APPLICATION_JSON) public Response jsonCreateRelationshipIndex( @HeaderParam(HEADER_TRANSACTION) ForceMode force, String json ) { try { return output.created( actions( force ).createRelationshipIndex( input.readMap( json ) ) ); } catch ( BadInputException e ) { return output.badRequest( e ); } catch ( IllegalArgumentException e ) { return output.badRequest( e ); } catch ( Exception e ) { return output.serverError( e ); } } @GET @Path(PATH_NAMED_NODE_INDEX) public Response getIndexedNodesByQuery( @PathParam("indexName") String indexName, @QueryParam("query") String query, @QueryParam("order") String order ) { try { return output.ok( actions.getIndexedNodesByQuery( indexName, query, order ) ); } catch ( NotFoundException nfe ) { return output.notFound( nfe ); } catch ( Exception e ) { return output.serverError( e ); } } @GET @Path(PATH_AUTO_INDEX) public Response getAutoIndexedNodesByQuery( @PathParam("type") String type, @QueryParam("query") String query ) { try { if ( type.equals( NODE_AUTO_INDEX_TYPE ) ) { return output.ok( actions.getAutoIndexedNodesByQuery( query ) ); } else if ( type.equals( RELATIONSHIP_AUTO_INDEX_TYPE ) ) { return output.ok( actions.getAutoIndexedRelationshipsByQuery( query ) ); } else { return output.badRequest( new RuntimeException( "Unrecognized auto-index type, " + "expected '" + NODE_AUTO_INDEX_TYPE + "' or '" + RELATIONSHIP_AUTO_INDEX_TYPE + "'" ) ); } } catch ( NotFoundException nfe ) { return output.notFound( nfe ); } catch ( Exception e ) { return output.serverError( e ); } } @DELETE @Path(PATH_NAMED_NODE_INDEX) @Consumes(MediaType.APPLICATION_JSON) public Response deleteNodeIndex( @HeaderParam(HEADER_TRANSACTION) ForceMode force, @PathParam("indexName") String indexName ) { try { actions( force ).removeNodeIndex( indexName ); return output.noContent(); } catch ( NotFoundException nfe ) { return output.notFound( nfe ); } catch ( UnsupportedOperationException e ) { return output.methodNotAllowed( e ); } } @DELETE @Path(PATH_NAMED_RELATIONSHIP_INDEX) @Consumes(MediaType.APPLICATION_JSON) public Response deleteRelationshipIndex( @HeaderParam(HEADER_TRANSACTION) ForceMode force, @PathParam("indexName") String indexName ) { try { actions( force ).removeRelationshipIndex( indexName ); return output.noContent(); } catch ( NotFoundException nfe ) { return output.notFound( nfe ); } catch ( UnsupportedOperationException e ) { return output.methodNotAllowed( e ); } } @POST @Path(PATH_NAMED_NODE_INDEX) @Consumes(MediaType.APPLICATION_JSON) public Response addToNodeIndex( @HeaderParam(HEADER_TRANSACTION) ForceMode force, @PathParam("indexName") String indexName, @QueryParam("unique") String unique, @QueryParam("uniqueness") String uniqueness, String postBody ) { try { Map<String, Object> entityBody; Pair<IndexedEntityRepresentation, Boolean> result; switch ( unique( unique, uniqueness ) ) { case GetOrCreate: entityBody = input.readMap( postBody, "key", "value" ); result = actions( force ).getOrCreateIndexedNode( indexName, String.valueOf( entityBody.get( "key" ) ), String.valueOf( entityBody.get( "value" ) ), extractNodeIdOrNull( getStringOrNull( entityBody, "uri" ) ), getMapOrNull( entityBody, "properties" ) ); return result.other() ? output.created( result.first() ) : output.okIncludeLocation( result.first () ); case CreateOrFail: entityBody = input.readMap( postBody, "key", "value" ); result = actions( force ).getOrCreateIndexedNode( indexName, String.valueOf( entityBody.get( "key" ) ), String.valueOf( entityBody.get( "value" ) ), extractNodeIdOrNull( getStringOrNull( entityBody, "uri" ) ), getMapOrNull( entityBody, "properties" ) ); if ( result.other() ) { return output.created( result.first() ); } String uri = getStringOrNull( entityBody, "uri" ); if ( uri == null ) { return output.conflict( result.first() ); } long idOfNodeToBeIndexed = extractNodeId( uri ); long idOfNodeAlreadyInIndex = extractNodeId( result.first().getIdentity() ); if ( idOfNodeToBeIndexed == idOfNodeAlreadyInIndex ) { return output.created( result.first() ); } return output.conflict( result.first() ); default: entityBody = input.readMap( postBody, "key", "value", "uri" ); return output.created( actions( force ).addToNodeIndex( indexName, String.valueOf( entityBody.get( "key" ) ), String.valueOf( entityBody.get( "value" ) ), extractNodeId( entityBody.get( "uri" ) .toString() ) ) ); } } catch ( UnsupportedOperationException e ) { return output.methodNotAllowed( e ); } catch ( IllegalArgumentException e ) { return output.badRequest( e ); } catch ( BadInputException e ) { return output.badRequest( e ); } catch ( Exception e ) { return output.serverError( e ); } } private DatabaseActions actions( ForceMode forceMode ) { return actions.forceMode( forceMode ); } @POST @Path(PATH_NAMED_RELATIONSHIP_INDEX) public Response addToRelationshipIndex( @HeaderParam(HEADER_TRANSACTION) ForceMode force, @PathParam("indexName") String indexName, @QueryParam("unique") String unique, @QueryParam("uniqueness") String uniqueness, String postBody ) { try { Map<String, Object> entityBody; Pair<IndexedEntityRepresentation, Boolean> result; switch ( unique( unique, uniqueness ) ) { case GetOrCreate: entityBody = input.readMap( postBody, "key", "value" ); result = actions( force ).getOrCreateIndexedRelationship( indexName, String.valueOf( entityBody.get( "key" ) ), String.valueOf( entityBody.get( "value" ) ), extractRelationshipIdOrNull( getStringOrNull ( entityBody, "uri" ) ), extractNodeIdOrNull( getStringOrNull( entityBody, "start" ) ), getStringOrNull( entityBody, "type" ), extractNodeIdOrNull( getStringOrNull( entityBody, "end" ) ), getMapOrNull( entityBody, "properties" ) ); return result.other() ? output.created( result.first() ) : output.ok( result.first() ); case CreateOrFail: entityBody = input.readMap( postBody, "key", "value" ); result = actions( force ).getOrCreateIndexedRelationship( indexName, String.valueOf( entityBody.get( "key" ) ), String.valueOf( entityBody.get( "value" ) ), extractRelationshipIdOrNull( getStringOrNull ( entityBody, "uri" ) ), extractNodeIdOrNull( getStringOrNull( entityBody, "start" ) ), getStringOrNull( entityBody, "type" ), extractNodeIdOrNull( getStringOrNull( entityBody, "end" ) ), getMapOrNull( entityBody, "properties" ) ); if ( result.other() ) { return output.created( result.first() ); } String uri = getStringOrNull( entityBody, "uri" ); if ( uri == null ) { return output.conflict( result.first() ); } long idOfRelationshipToBeIndexed = extractRelationshipId( uri ); long idOfRelationshipAlreadyInIndex = extractRelationshipId( result.first().getIdentity() ); if ( idOfRelationshipToBeIndexed == idOfRelationshipAlreadyInIndex ) { return output.created( result.first() ); } return output.conflict( result.first() ); default: entityBody = input.readMap( postBody, "key", "value", "uri" ); return output.created( actions( force ).addToRelationshipIndex( indexName, String.valueOf( entityBody.get( "key" ) ), String.valueOf( entityBody.get( "value" ) ), extractRelationshipId( entityBody.get( "uri" ).toString() ) ) ); } } catch ( UnsupportedOperationException e ) { return output.methodNotAllowed( e ); } catch ( IllegalArgumentException e ) { return output.badRequest( e ); } catch ( BadInputException e ) { return output.badRequest( e ); } catch ( Exception e ) { return output.serverError( e ); } } private UniqueIndexType unique( String uniqueParam, String uniquenessParam ) { UniqueIndexType unique = UniqueIndexType.None; if ( uniquenessParam == null || uniquenessParam.equals( "" ) ) { // Backward compatibility check if ( "".equals( uniqueParam ) || Boolean.parseBoolean( uniqueParam ) ) { unique = UniqueIndexType.GetOrCreate; } } else if ( UNIQUENESS_MODE_GET_OR_CREATE.equalsIgnoreCase( uniquenessParam ) ) { unique = UniqueIndexType.GetOrCreate; } else if ( UNIQUENESS_MODE_CREATE_OR_FAIL.equalsIgnoreCase( uniquenessParam ) ) { unique = UniqueIndexType.CreateOrFail; } return unique; } private String getStringOrNull( Map<String, Object> map, String key ) throws BadInputException { Object object = map.get( key ); if ( object instanceof String ) { return (String) object; } if ( object == null ) { return null; } throw new BadInputException( "\"" + key + "\" should be a string" ); } @SuppressWarnings("unchecked") private static Map<String, Object> getMapOrNull( Map<String, Object> data, String key ) throws BadInputException { Object object = data.get( key ); if ( object instanceof Map<?, ?> ) { return (Map<String, Object>) object; } if ( object == null ) { return null; } throw new BadInputException( "\"" + key + "\" should be a map" ); } @GET @Path(PATH_NODE_INDEX_ID) public Response getNodeFromIndexUri( @PathParam("indexName") String indexName, @PathParam("key") String key, @PathParam("value") String value, @PathParam("id") long id ) { try { return output.ok( actions.getIndexedNode( indexName, key, value, id ) ); } catch ( NotFoundException nfe ) { return output.notFound( nfe ); } catch ( Exception e ) { return output.serverError( e ); } } @GET @Path(PATH_RELATIONSHIP_INDEX_ID) public Response getRelationshipFromIndexUri( @PathParam("indexName") String indexName, @PathParam("key") String key, @PathParam("value") String value, @PathParam("id") long id ) { return output.ok( actions.getIndexedRelationship( indexName, key, value, id ) ); } @GET @Path(PATH_NODE_INDEX_GET) public Response getIndexedNodes( @PathParam("indexName") String indexName, @PathParam("key") String key, @PathParam("value") String value ) { try { return output.ok( actions.getIndexedNodes( indexName, key, value ) ); } catch ( NotFoundException nfe ) { return output.notFound( nfe ); } catch ( Exception e ) { return output.serverError( e ); } } @GET @Path(PATH_AUTO_INDEX_GET) public Response getAutoIndexedNodes( @PathParam("type") String type, @PathParam("key") String key, @PathParam("value") String value ) { try { if ( type.equals( NODE_AUTO_INDEX_TYPE ) ) { return output.ok( actions.getAutoIndexedNodes( key, value ) ); } else if ( type.equals( RELATIONSHIP_AUTO_INDEX_TYPE ) ) { return output.ok( actions.getAutoIndexedRelationships( key, value ) ); } else { return output.badRequest( new RuntimeException( "Unrecognized auto-index type, " + "expected '" + NODE_AUTO_INDEX_TYPE + "' or '" + RELATIONSHIP_AUTO_INDEX_TYPE + "'" ) ); } } catch ( NotFoundException nfe ) { return output.notFound( nfe ); } catch ( Exception e ) { return output.serverError( e ); } } @GET @Path(PATH_NODE_INDEX_QUERY_WITH_KEY) public Response getIndexedNodesByQuery( @PathParam("indexName") String indexName, @PathParam("key") String key, @QueryParam("query") String query, @PathParam("order") String order ) { try { return output.ok( actions.getIndexedNodesByQuery( indexName, key, query, order ) ); } catch ( NotFoundException nfe ) { return output.notFound( nfe ); } catch ( Exception e ) { return output.serverError( e ); } } @GET @Path(PATH_RELATIONSHIP_INDEX_GET) public Response getIndexedRelationships( @PathParam("indexName") String indexName, @PathParam("key") String key, @PathParam("value") String value ) { try { return output.ok( actions.getIndexedRelationships( indexName, key, value ) ); } catch ( NotFoundException nfe ) { return output.notFound( nfe ); } catch ( Exception e ) { return output.serverError( e ); } } @GET @Path(PATH_AUTO_INDEX_STATUS) public Response isAutoIndexerEnabled( @PathParam("type") String type ) { return output.ok( actions.isAutoIndexerEnabled( type ) ); } @PUT @Path(PATH_AUTO_INDEX_STATUS) public Response setAutoIndexerEnabled( @PathParam("type") String type, String enable ) { actions.setAutoIndexerEnabled( type, Boolean.parseBoolean( enable ) ); return output.ok( Representation.emptyRepresentation() ); } @GET @Path(PATH_AUTO_INDEXED_PROPERTIES) public Response getAutoIndexedProperties( @PathParam("type") String type ) { return output.ok( actions.getAutoIndexedProperties( type ) ); } @POST @Path(PATH_AUTO_INDEXED_PROPERTIES) public Response startAutoIndexingProperty( @PathParam("type") String type, String property ) { actions.startAutoIndexingProperty( type, property ); return output.ok( Representation.emptyRepresentation() ); } @DELETE @Path(PATH_AUTO_INDEX_PROPERTY_DELETE) public Response stopAutoIndexingProperty( @PathParam("type") String type, @PathParam("property") String property ) { actions.stopAutoIndexingProperty( type, property ); return output.ok( Representation.emptyRepresentation() ); } @GET @Path(PATH_NAMED_RELATIONSHIP_INDEX) public Response getIndexedRelationshipsByQuery( @PathParam("indexName") String indexName, @QueryParam("query") String query, @QueryParam("order") String order ) { try { return output.ok( actions.getIndexedRelationshipsByQuery( indexName, query, order ) ); } catch ( NotFoundException nfe ) { return output.notFound( nfe ); } catch ( Exception e ) { return output.serverError( e ); } } @GET @Path(PATH_RELATIONSHIP_INDEX_QUERY_WITH_KEY) public Response getIndexedRelationshipsByQuery( @PathParam("indexName") String indexName, @PathParam("key") String key, @QueryParam("query") String query, @QueryParam("order") String order ) { try { return output.ok( actions.getIndexedRelationshipsByQuery( indexName, key, query, order ) ); } catch ( NotFoundException nfe ) { return output.notFound( nfe ); } catch ( Exception e ) { return output.serverError( e ); } } @DELETE @Path(PATH_NODE_INDEX_ID) public Response deleteFromNodeIndex( @HeaderParam(HEADER_TRANSACTION) ForceMode force, @PathParam("indexName") String indexName, @PathParam("key") String key, @PathParam("value") String value, @PathParam("id") long id ) { try { actions( force ).removeFromNodeIndex( indexName, key, value, id ); return nothing(); } catch ( UnsupportedOperationException e ) { return output.methodNotAllowed( e ); } catch ( NotFoundException nfe ) { return output.notFound( nfe ); } catch ( Exception e ) { return output.serverError( e ); } } @DELETE @Path(PATH_NODE_INDEX_REMOVE_KEY) public Response deleteFromNodeIndexNoValue( @HeaderParam(HEADER_TRANSACTION) ForceMode force, @PathParam("indexName") String indexName, @PathParam("key") String key, @PathParam("id") long id ) { try { actions( force ).removeFromNodeIndexNoValue( indexName, key, id ); return nothing(); } catch ( UnsupportedOperationException e ) { return output.methodNotAllowed( e ); } catch ( NotFoundException nfe ) { return output.notFound( nfe ); } catch ( Exception e ) { return output.serverError( e ); } } @DELETE @Path(PATH_NODE_INDEX_REMOVE) public Response deleteFromNodeIndexNoKeyValue( @HeaderParam(HEADER_TRANSACTION) ForceMode force, @PathParam("indexName") String indexName, @PathParam("id") long id ) { try { actions( force ).removeFromNodeIndexNoKeyValue( indexName, id ); return nothing(); } catch ( UnsupportedOperationException e ) { return output.methodNotAllowed( e ); } catch ( NotFoundException nfe ) { return output.notFound( nfe ); } catch ( Exception e ) { return output.serverError( e ); } } @DELETE @Path(PATH_RELATIONSHIP_INDEX_ID) public Response deleteFromRelationshipIndex( @HeaderParam(HEADER_TRANSACTION) ForceMode force, @PathParam("indexName") String indexName, @PathParam("key") String key, @PathParam("value") String value, @PathParam("id") long id ) { try { actions( force ).removeFromRelationshipIndex( indexName, key, value, id ); return nothing(); } catch ( UnsupportedOperationException e ) { return output.methodNotAllowed( e ); } catch ( NotFoundException nfe ) { return output.notFound( nfe ); } catch ( Exception e ) { return output.serverError( e ); } } @DELETE @Path(PATH_RELATIONSHIP_INDEX_REMOVE_KEY) public Response deleteFromRelationshipIndexNoValue( @HeaderParam(HEADER_TRANSACTION) ForceMode force, @PathParam("indexName") String indexName, @PathParam("key") String key, @PathParam("id") long id ) { try { actions( force ).removeFromRelationshipIndexNoValue( indexName, key, id ); return nothing(); } catch ( UnsupportedOperationException e ) { return output.methodNotAllowed( e ); } catch ( NotFoundException nfe ) { return output.notFound( nfe ); } catch ( Exception e ) { return output.serverError( e ); } } @DELETE @Path(PATH_RELATIONSHIP_INDEX_REMOVE) public Response deleteFromRelationshipIndex( @HeaderParam(HEADER_TRANSACTION) ForceMode force, @PathParam("indexName") String indexName, @PathParam("id") long id ) { try { actions( force ).removeFromRelationshipIndexNoKeyValue( indexName, id ); return nothing(); } catch ( UnsupportedOperationException e ) { return output.methodNotAllowed( e ); } catch ( NotFoundException nfe ) { return output.notFound( nfe ); } catch ( Exception e ) { return output.serverError( e ); } } // Traversal @POST @Path(PATH_NODE_TRAVERSE) public Response traverse( @PathParam("nodeId") long startNode, @PathParam("returnType") TraverserReturnType returnType, String body ) { try { return output.ok( actions.traverse( startNode, input.readMap( body ), returnType ) ); } catch ( EvaluationException e ) { return output.badRequest( e ); } catch ( BadInputException e ) { return output.badRequest( e ); } catch ( NotFoundException e ) { return output.notFound( e ); } } // Paged traversal @DELETE @Path(PATH_TO_PAGED_TRAVERSERS) public Response removePagedTraverser( @PathParam("traverserId") String traverserId ) { if ( actions.removePagedTraverse( traverserId ) ) { return output.ok(); } else { return output.notFound(); } } @GET @Path(PATH_TO_PAGED_TRAVERSERS) public Response pagedTraverse( @PathParam("traverserId") String traverserId, @PathParam("returnType") TraverserReturnType returnType ) { try { return output.ok( actions.pagedTraverse( traverserId, returnType ) ); } catch ( EvaluationException e ) { return output.badRequest( e ); } catch ( NotFoundException e ) { return output.notFound( e ); } } @POST @Path(PATH_TO_CREATE_PAGED_TRAVERSERS) public Response createPagedTraverser( @PathParam("nodeId") long startNode, @PathParam("returnType") TraverserReturnType returnType, @QueryParam("pageSize") @DefaultValue(FIFTY_ENTRIES) int pageSize, @QueryParam("leaseTime") @DefaultValue(SIXTY_SECONDS) int leaseTimeInSeconds, String body ) { try { validatePageSize( pageSize ); validateLeaseTime( leaseTimeInSeconds ); String traverserId = actions.createPagedTraverser( startNode, input.readMap( body ), pageSize, leaseTimeInSeconds ); URI uri = new URI( "node/" + startNode + "/paged/traverse/" + returnType + "/" + traverserId ); return output.created( new ListEntityRepresentation( actions.pagedTraverse( traverserId, returnType ), uri.normalize() ) ); } catch ( EvaluationException e ) { return output.badRequest( e ); } catch ( BadInputException e ) { return output.badRequest( e ); } catch ( NotFoundException e ) { return output.notFound( e ); } catch ( URISyntaxException e ) { return output.serverError( e ); } } private void validateLeaseTime( int leaseTimeInSeconds ) throws BadInputException { if ( leaseTimeInSeconds < 1 ) { throw new BadInputException( "Lease time less than 1 second is not supported" ); } } private void validatePageSize( int pageSize ) throws BadInputException { if ( pageSize < 1 ) { throw new BadInputException( "Page size less than 1 is not permitted" ); } } @POST @Path(PATH_NODE_PATH) public Response singlePath( @PathParam("nodeId") long startNode, String body ) { final Map<String, Object> description; final long endNode; try { description = input.readMap( body ); endNode = extractNodeId( (String) description.get( "to" ) ); return output.ok( actions.findSinglePath( startNode, endNode, description ) ); } catch ( BadInputException e ) { return output.badRequest( e ); } catch ( ClassCastException e ) { return output.badRequest( e ); } catch ( NotFoundException e ) { return output.notFound( e ); } } @POST @Path(PATH_NODE_PATHS) public Response allPaths( @PathParam("nodeId") long startNode, String body ) { final Map<String, Object> description; final long endNode; try { description = input.readMap( body ); endNode = extractNodeId( (String) description.get( "to" ) ); return output.ok( actions.findPaths( startNode, endNode, description ) ); } catch ( BadInputException e ) { return output.badRequest( e ); } catch ( ClassCastException e ) { return output.badRequest( e ); } } @POST @Path( PATH_SCHEMA_INDEX_LABEL ) public Response createSchemaIndex( @PathParam( "label" ) String labelName, String body ) { try { Map<String, Object> data = input.readMap( body, "property_keys" ); Iterable<String> singlePropertyKey = singleOrList( data, "property_keys" ); if ( singlePropertyKey == null ) { return output.badRequest( new IllegalArgumentException( "Supply single property key or list of property keys" ) ); } return output.ok( actions.createSchemaIndex( labelName, singlePropertyKey ) ); } catch( UnsupportedOperationException e ) { return output.badRequest( e ); } catch ( BadInputException e ) { return output.badRequest( e ); } catch ( ConstraintViolationException e ) { return output.conflict( e ); } } private Iterable<String> singleOrList( Map<String, Object> data, String key ) { Object propertyKeys = data.get( key ); Iterable<String> singlePropertyKey = null; if ( propertyKeys instanceof List ) singlePropertyKey = (List<String>) propertyKeys; else if ( propertyKeys instanceof String ) singlePropertyKey = Arrays.asList((String)propertyKeys); return singlePropertyKey; } @DELETE @Path( PATH_SCHEMA_INDEX_LABEL_PROPERTY ) public Response dropSchemaIndex( @PathParam( "label" ) String labelName, @PathParam( "property" ) AmpersandSeparatedCollection properties ) { // TODO assumption, only a single property key if ( properties.size() != 1 ) { return output.badRequest( new IllegalArgumentException( "Single property key assumed" ) ); } String property = single( properties ); try { if ( actions.dropSchemaIndex( labelName, property ) ) return nothing(); else return output.notFound(); } catch ( ConstraintViolationException e ) { return output.conflict( e ); } } @GET @Path( PATH_SCHEMA_INDEX ) public Response getSchemaIndexes() { return output.ok( actions.getSchemaIndexes() ); } @GET @Path( PATH_SCHEMA_INDEX_LABEL ) public Response getSchemaIndexesForLabel( @PathParam("label") String labelName ) { return output.ok( actions.getSchemaIndexes( labelName ) ); } @POST @Path( PATH_SCHEMA_CONSTRAINT_LABEL_UNIQUENESS ) public Response createPropertyUniquenessConstraint( @PathParam( "label" ) String labelName, String body ) { try { Map<String, Object> data = input.readMap( body, "property_keys" ); Iterable<String> singlePropertyKey = singleOrList( data, "property_keys" ); if ( singlePropertyKey == null ) { return output.badRequest( new IllegalArgumentException( "Supply single property key or list of property keys" ) ); } return output.ok( actions.createPropertyUniquenessConstraint( labelName, singlePropertyKey ) ); } catch( UnsupportedOperationException e ) { return output.badRequest( e ); } catch ( BadInputException e ) { return output.badRequest( e ); } catch ( ConstraintViolationException e ) { return output.conflict( e ); } } @DELETE @Path( PATH_SCHEMA_CONSTRAINT_LABEL_UNIQUENESS_PROPERTY ) public Response dropPropertyUniquenessConstraint( @PathParam( "label" ) String labelName, @PathParam( "property" ) AmpersandSeparatedCollection properties ) { try { if ( actions.dropPropertyUniquenessConstraint( labelName, properties ) ) return nothing(); else return output.notFound(); } catch ( ConstraintViolationException e ) { return output.conflict( e ); } } @GET @Path(PATH_SCHEMA_CONSTRAINT) public Response getSchemaConstraints() { return output.ok( actions.getConstraints() ); } @GET @Path( PATH_SCHEMA_CONSTRAINT_LABEL ) public Response getSchemaConstraintsForLabel( @PathParam( "label" ) String labelName ) { return output.ok( actions.getLabelConstraints( labelName ) ); } @GET @Path( PATH_SCHEMA_CONSTRAINT_LABEL_UNIQUENESS ) public Response getSchemaConstraintsForLabelAndUniqueness( @PathParam( "label" ) String labelName ) { return output.ok( actions.getLabelUniquenessConstraints( labelName ) ); } @GET @Path( PATH_SCHEMA_CONSTRAINT_LABEL_UNIQUENESS_PROPERTY ) public Response getSchemaConstraintsForLabelAndPropertyUniqueness( @PathParam( "label" ) String labelName, @PathParam( "property" ) AmpersandSeparatedCollection propertyKeys ) { try { ListRepresentation constraints = actions.getPropertyUniquenessConstraint( labelName, propertyKeys ); return output.ok( constraints ); } catch ( IllegalArgumentException e ) { return output.notFound( e ); } } private final Function<Map.Entry<String,List<String>>,Pair<String,Object>> queryParamsToProperties = new Function<Map.Entry<String, List<String>>, Pair<String, Object>>() { @Override public Pair<String, Object> apply( Map.Entry<String, List<String>> queryEntry ) { try { Object propertyValue = input.readValue( queryEntry.getValue().get( 0 ) ); if ( propertyValue instanceof Collection<?> ) { propertyValue = PropertySettingStrategy.convertToNativeArray( (Collection<?>) propertyValue ); } return Pair.of( queryEntry.getKey(), propertyValue ); } catch ( BadInputException e ) { throw new IllegalArgumentException( String.format( "Unable to deserialize property value for %s.", queryEntry.getKey() ), e ); } } }; }
false
community_server_src_main_java_org_neo4j_server_rest_web_RestfulGraphDatabase.java
2,724
@Path( "/resource" ) public class ResourcesService { final static String JAVASCRIPT_BODY; static { // FIXME This is so very ugly, it's because when running it with maven // it won't add the src/main/resources to the classpath String body = null; try { body = readResourceAsString( "htmlbrowse.js" ); } catch ( Exception e ) { body = readFileAsString( "src/main/resources/htmlbrowse.js" ); } JAVASCRIPT_BODY = body; } public ResourcesService( @Context UriInfo uriInfo ) { } @GET @Path( "htmlbrowse.js" ) public String getHtmlBrowseJavascript() { return JAVASCRIPT_BODY; } private static String readFileAsString( String file ) { try { return readAsString( new FileInputStream( file ) ); } catch ( IOException e ) { throw new RuntimeException( e ); } } private static String readResourceAsString( String resource ) { return readAsString( ClassLoader.getSystemResourceAsStream( resource ) ); } private static String readAsString( InputStream input ) { final char[] buffer = new char[0x10000]; StringBuilder out = new StringBuilder(); Reader reader = null; try { reader = new InputStreamReader( input, "UTF-8" ); int read; do { read = reader.read( buffer, 0, buffer.length ); if ( read > 0 ) { out.append( buffer, 0, read ); } } while ( read >= 0 ); } catch ( IOException e ) { throw new RuntimeException( e ); } finally { if ( reader != null ) { try { reader.close(); } catch ( IOException e ) { // OK } } } return out.toString(); } }
false
community_server_src_main_java_org_neo4j_server_rest_web_ResourcesService.java
2,725
public class RelationshipNotFoundException extends Exception { private static final long serialVersionUID = -1177555212368703516L; }
false
community_server-api_src_main_java_org_neo4j_server_rest_web_RelationshipNotFoundException.java
2,726
public class PropertyValueException extends BadInputException { private static final long serialVersionUID = -7810255514347322861L; public PropertyValueException( String key, Object value ) { super( "Could not set property \"" + key + "\", unsupported type: " + value ); } public PropertyValueException( String message, Throwable cause ) { super( message, cause ); } public PropertyValueException( String message ) { super( message ); } public PropertyValueException( Throwable cause ) { super( cause ); } }
false
community_server_src_main_java_org_neo4j_server_rest_web_PropertyValueException.java
2,727
public class PathNotFoundException extends Exception { private static final long serialVersionUID = 3067232188093597955L; }
false
community_server_src_main_java_org_neo4j_server_rest_web_PathNotFoundException.java
2,728
public class PagingTraversalTest { 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 static final int SIXTY_SECONDS = 60; 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( enoughMinutesToExpireTheTraversal(), TimeUnit.MINUTES ); String traverserId = parseTraverserIdFromLocationUri( response ); response = service.pagedTraverse( traverserId, TraverserReturnType.node ); assertEquals( 404, response.getStatus() ); } private int enoughMinutesToExpireTheTraversal() { return 10; } @Test public void shouldRespondWith400OnNegativePageSize() { long arbitraryStartNodeId = 1l; int negativePageSize = -5; String arbitraryDescription = description(); Response response = service.createPagedTraverser( arbitraryStartNodeId, TraverserReturnType.node, negativePageSize, SIXTY_SECONDS, arbitraryDescription ); assertEquals( 400, response.getStatus() ); } @Test public void shouldRespondWith400OnLeaseTime() { long arbitraryStartNodeId = 1l; int arbitraryPageSize = 5; String arbitraryDescription = description(); Response response = service.createPagedTraverser( arbitraryStartNodeId, TraverserReturnType.node, arbitraryPageSize, -5, arbitraryDescription ); assertEquals( 400, 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( this.enoughMinutesToExpireTheTraversal(), TimeUnit.MINUTES ); response = service.pagedTraverse( traverserId, TraverserReturnType.node ); assertEquals( 404, response.getStatus() ); } @Test public void shouldBeAbleToRemoveALeaseOnceOnly() { Response response = createAPagedTraverser(); String traverserId = parseTraverserIdFromLocationUri( response ); assertEquals( 200, service.removePagedTraverser( traverserId ) .getStatus() ); assertEquals( 404, service.removePagedTraverser( traverserId ) .getStatus() ); } private Response createAPagedTraverser() { long startNodeId = createListOfNodes( 1000 ); String description = description(); final int PAGE_SIZE = 10; return service.createPagedTraverser( startNodeId, TraverserReturnType.node, PAGE_SIZE, SIXTY_SECONDS, description ); } private String description() { return "{" + "\"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\"}" + "}"; } 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_PagingTraversalTest.java
2,729
public class OperationFailureException extends Exception { public OperationFailureException( String message ) { super( message ); } private static final long serialVersionUID = -4594462038185850546L; }
false
community_server_src_main_java_org_neo4j_server_rest_web_OperationFailureException.java
2,730
public class NodeNotFoundException extends Exception { public NodeNotFoundException( String message ) { super(message); } public NodeNotFoundException( NotFoundException e ) { super(e); } private static final long serialVersionUID = 7292603734007524712L; }
false
community_server-api_src_main_java_org_neo4j_server_rest_web_NodeNotFoundException.java
2,731
public class NoSuchPropertyException extends Exception { private static final long serialVersionUID = -2078314214014212029L; public NoSuchPropertyException( PropertyContainer entity, String key ) { super( entity + " does not have a property \"" + key + "\"" ); } }
false
community_server_src_main_java_org_neo4j_server_rest_web_NoSuchPropertyException.java
2,732
public static class DomainModel { public Map<URI, DomainEntity> nodeUriToEntityMap = new HashMap<URI, DomainEntity>(); String nodeIndexName = "nodes"; public Map<String, String> indexedNodeKeyValues = new HashMap<String, String>(); public Map<URI, DomainEntity> indexedNodeUriToEntityMap = new HashMap<URI, DomainEntity>(); String relationshipIndexName = "relationships"; public Map<URI, DomainEntity> indexedRelationshipUriToEntityMap = new HashMap<URI, DomainEntity>(); public Map<String, String> indexedRelationshipKeyValues = new HashMap<String, String>(); public void add( DomainEntity de ) { nodeUriToEntityMap.put( de.location, de ); } }
false
community_server_src_test_java_org_neo4j_server_rest_web_ModelBuilder.java
2,733
public static class DomainEntity { public URI location; public Map<String, String> properties = new HashMap<String, String>(); }
false
community_server_src_test_java_org_neo4j_server_rest_web_ModelBuilder.java
2,734
public class ModelBuilder { private static final ForceMode FORCE = ForceMode.forced; public static DomainModel generateMatrix( RestfulGraphDatabase rgd ) { String key = "key_get"; String value = "value"; DomainModel dm = new DomainModel(); DomainEntity thomas = new DomainEntity(); thomas.properties.put( "name", "Thomas Anderson" ); thomas.location = (URI) rgd.createNode( FORCE, "{\"name\":\"" + "Thomas Anderson" + "\"}" ) .getMetadata() .getFirst( "Location" ); dm.add( thomas ); DomainEntity agent = new DomainEntity(); agent.properties.put( "name", "Agent Smith" ); agent.location = (URI) rgd.createNode( FORCE, "{\"name\":\"" + "Agent Smith" + "\"}" ) .getMetadata() .getFirst( "Location" ); dm.add( agent ); dm.nodeIndexName = "matrixal-nodes"; dm.indexedNodeKeyValues.put( key, value ); dm.indexedNodeUriToEntityMap.put( (URI) rgd.addToNodeIndex( FORCE, dm.nodeIndexName, null, null, "{\"key\": \"" + key + "\", \"value\":\"" + value + "\", \"uri\": \"" + thomas.location + "\"}" ) .getMetadata() .getFirst( "Location" ), thomas ); dm.indexedNodeUriToEntityMap.put( (URI) rgd.addToNodeIndex( FORCE, dm.nodeIndexName, null, null, "{\"key\": \"" + key + "\", \"value\":\"" + value + "\", \"uri\": \"" + agent.location + "\"}" ) .getMetadata() .getFirst( "Location" ), agent ); return dm; } public static class DomainEntity { public URI location; public Map<String, String> properties = new HashMap<String, String>(); } public static class DomainModel { public Map<URI, DomainEntity> nodeUriToEntityMap = new HashMap<URI, DomainEntity>(); String nodeIndexName = "nodes"; public Map<String, String> indexedNodeKeyValues = new HashMap<String, String>(); public Map<URI, DomainEntity> indexedNodeUriToEntityMap = new HashMap<URI, DomainEntity>(); String relationshipIndexName = "relationships"; public Map<URI, DomainEntity> indexedRelationshipUriToEntityMap = new HashMap<URI, DomainEntity>(); public Map<String, String> indexedRelationshipKeyValues = new HashMap<String, String>(); public void add( DomainEntity de ) { nodeUriToEntityMap.put( de.location, de ); } } }
false
community_server_src_test_java_org_neo4j_server_rest_web_ModelBuilder.java
2,735
private class Output extends ServletOutputStream { private final ByteArrayOutputStream baos = new ByteArrayOutputStream(); @Override public void write( int c ) throws IOException { baos.write( c ); } @Override public String toString() { try { baos.flush(); return baos.toString("UTF-8"); } catch ( Exception e ) { throw new RuntimeException( e); } } }
false
community_server_src_main_java_org_neo4j_server_rest_web_InternalJettyServletResponse.java
2,736
public class InternalJettyServletResponse extends Response { private class Output extends ServletOutputStream { private final ByteArrayOutputStream baos = new ByteArrayOutputStream(); @Override public void write( int c ) throws IOException { baos.write( c ); } @Override public String toString() { try { baos.flush(); return baos.toString("UTF-8"); } catch ( Exception e ) { throw new RuntimeException( e); } } } private final Map<String, Object> headers = new HashMap<>(); private final Output output = new Output(); private int status = -1; private String message = ""; public InternalJettyServletResponse() { super( null, null ); } @Override public void addCookie( Cookie cookie ) { // TODO Auto-generated method stub } @Override public String encodeURL( String url ) { // TODO Auto-generated method stub return null; } @Override public void sendError( int sc ) throws IOException { sendError( sc, null ); } @Override public void sendError( int code, String message ) throws IOException { setStatus( code, message ); } @Override public void sendRedirect( String location ) throws IOException { setStatus( 304 ); addHeader( "location", location ); } @Override public boolean containsHeader( String name ) { return headers.containsKey( name ); } @Override public void setDateHeader( String name, long date ) { headers.put( name, date ); } @Override public void addDateHeader( String name, long date ) { if ( headers.containsKey( name ) ) { headers.put( name, date ); } } @Override public void addHeader( String name, String value ) { setHeader( name, value ); } @Override public void setHeader( String name, String value ) { headers.put( name, value ); } @Override public void setIntHeader( String name, int value ) { headers.put( name, value ); } @Override public void addIntHeader( String name, int value ) { setIntHeader( name, value ); } @Override public String getHeader( String name ) { if ( headers.containsKey( name ) ) { Object value = headers.get( name ); if ( value instanceof String ) { return (String) value; } else if ( value instanceof Collection ) { return ( (Collection<?>) value ).iterator() .next() .toString(); } else { return value.toString(); } } return null; } public Map<String, Object> getHeaders() { return headers; } @Override public Collection<String> getHeaders( String name ) { if ( headers.containsKey( name ) ) { Object value = headers.get( name ); if ( value instanceof Collection ) { return (Collection<String>) value; } else { return Collections.singleton( (String) value ); } } return null; } @Override public void setStatus( int sc ) { status = sc; } @Override public void setStatus( int sc, String sm ) { status = sc; message = sm; } @Override public int getStatus() { return status; } @Override public String getReason() { return message; } @Override public ServletOutputStream getOutputStream() throws IOException { return output; } @Override public boolean isWriting() { return false; } @Override public PrintWriter getWriter() throws IOException { return new PrintWriter( new OutputStreamWriter( output, "UTF-8") ); } @Override public void setCharacterEncoding( String encoding ) { } @Override public void setContentLength( int len ) { } @Override public void setLongContentLength( long len ) { } @Override public void setContentType( String contentType ) { } @Override public void setBufferSize( int size ) { } @Override public int getBufferSize() { return -1; } @Override public void flushBuffer() throws IOException { } @Override public String toString() { return null; } @Override public HttpFields getHttpFields() { return null; } @Override public long getContentCount() { return 1l; } public void complete() throws IOException { } @Override public void setLocale( Locale locale ) { } @Override public boolean isCommitted() { return false; } }
false
community_server_src_main_java_org_neo4j_server_rest_web_InternalJettyServletResponse.java
2,737
private class Input extends ServletInputStream { private final byte[] bytes; private int position = 0; public Input( String data ) { try { bytes = data.getBytes("UTF-8"); } catch ( UnsupportedEncodingException e ) { throw new RuntimeException( e ); } } public int read() throws IOException { if ( bytes.length > position ) return (int) bytes[position++]; return -1; } public int length() { return bytes.length; } public long contentRead() { return (long) position; } }
false
community_server_src_main_java_org_neo4j_server_rest_web_InternalJettyServletRequest.java
2,738
public class InternalJettyServletRequest extends Request { private class Input extends ServletInputStream { private final byte[] bytes; private int position = 0; public Input( String data ) { try { bytes = data.getBytes("UTF-8"); } catch ( UnsupportedEncodingException e ) { throw new RuntimeException( e ); } } public int read() throws IOException { if ( bytes.length > position ) return (int) bytes[position++]; return -1; } public int length() { return bytes.length; } public long contentRead() { return (long) position; } } private final Map<String, Object> headers; private final Cookie[] cookies; private final Input input; private final BufferedReader inputReader; private String contentType; private final String method; private final InternalJettyServletResponse response; public InternalJettyServletRequest( String method, String uri, String body, InternalJettyServletResponse res ) throws UnsupportedEncodingException { this( method, new HttpURI( uri ), body, new Cookie[] {}, MediaType.APPLICATION_JSON, "UTF-8", res ); } public InternalJettyServletRequest( String method, HttpURI uri, String body, Cookie[] cookies, String contentType, String encoding, InternalJettyServletResponse res ) throws UnsupportedEncodingException { super( null, null ); this.input = new Input( body ); this.inputReader = new BufferedReader( new StringReader( body ) ); this.contentType = contentType; this.cookies = cookies; this.method = method; this.response = res; this.headers = new HashMap<>(); setUri( uri ); setCharacterEncoding( encoding ); setRequestURI( null ); setQueryString( null ); setScheme(uri.getScheme()); setDispatcherType( DispatcherType.REQUEST ); } @Override public int getContentLength() { return input.length(); } @Override public String getContentType() { return contentType; } public void setContentType( String contentType ) { this.contentType = contentType; } public long getContentRead() { return input.contentRead(); } @Override public ServletInputStream getInputStream() throws IOException { return input; } @Override public String getProtocol() { return "HTTP/1.1"; } @Override public BufferedReader getReader() throws IOException { return inputReader; } @Override public String getRemoteAddr() { return null; } @Override public String getRemoteHost() { return null; } @Override public boolean isSecure() { return false; } @Override public int getRemotePort() { return 0; } @Override public String getLocalName() { return null; } @Override public String getLocalAddr() { return null; } @Override public int getLocalPort() { return 0; } @Override public String getAuthType() { return null; } @Override public Cookie[] getCookies() { return cookies; } public void addHeader(String header, String value) { headers.put(header, value); } @Override public long getDateHeader( String name ) { if ( headers.containsKey( name ) ) { return (Long) headers.get( name ); } return -1; } @Override public String getHeader( String name ) { if ( headers.containsKey( name ) ) { Object value = headers.get( name ); if ( value instanceof String ) { return (String) value; } else if ( value instanceof Collection ) { return ( (Collection<?>) value ).iterator() .next() .toString(); } else { return value.toString(); } } return null; } @Override public Enumeration<String> getHeaders( String name ) { if ( headers.containsKey( name ) ) { Object value = headers.get( name ); if ( value instanceof Collection ) { return Collections.enumeration( (Collection<String>) value ); } else { return Collections.enumeration( Collections.singleton( (String) value ) ); } } return null; } @Override public Enumeration<String> getHeaderNames() { return Collections.enumeration( headers.keySet() ); } @Override public int getIntHeader( String name ) { if ( headers.containsKey( name ) ) { return (Integer) headers.get( name ); } return -1; } @Override public String getMethod() { return method; } @Override public Response getResponse() { return response; } @Override public String toString() { return String.format( "%s %s %s\n%s", getMethod(), getUri(), getProtocol(), getHttpFields() ); } }
false
community_server_src_main_java_org_neo4j_server_rest_web_InternalJettyServletRequest.java
2,739
{ @Override protected void serialize( MappingSerializer serializer ) { for ( String extension : extensions.extensionNames() ) { serializer.putUri( extension, "ext/" + extension ); } } };
false
community_server_src_main_java_org_neo4j_server_rest_web_ExtensionService.java
2,740
{ @Override public IndexDefinitionRepresentation apply( IndexDefinition definition ) { return new IndexDefinitionRepresentation( definition ); } }, definitions );
false
community_server_src_main_java_org_neo4j_server_rest_web_DatabaseActions.java
2,741
{ @Override public ValueRepresentation apply( Label label ) { return ValueRepresentation.string( label.name() ); } }, GlobalGraphOperations.at( graphDb ).getAllLabels() ) );
false
community_server_src_main_java_org_neo4j_server_rest_web_DatabaseActions.java
2,742
public class TransactionHandle { private final TransitionalPeriodTransactionMessContainer txManagerFacade; private final ExecutionEngine engine; private final TransactionRegistry registry; private final TransactionUriScheme uriScheme; private final StringLogger log; private final long id; private TransitionalTxManagementKernelTransaction context; public TransactionHandle( TransitionalPeriodTransactionMessContainer txManagerFacade, ExecutionEngine engine, TransactionRegistry registry, TransactionUriScheme uriScheme, StringLogger log ) { this.txManagerFacade = txManagerFacade; this.engine = engine; this.registry = registry; this.uriScheme = uriScheme; this.log = log; this.id = registry.begin(); } public URI uri() { return uriScheme.txUri( id ); } public void execute( StatementDeserializer statements, ExecutionResultSerializer output ) { List<Neo4jError> errors = new LinkedList<>(); try { output.transactionCommitUri( uriScheme.txCommitUri( id ) ); ensureActiveTransaction(); execute( statements, output, errors ); } catch ( InternalBeginTransactionError e ) { errors.add( e.toNeo4jError() ); } finally { output.errors( errors ); output.finish(); } } public void commit( StatementDeserializer statements, ExecutionResultSerializer output ) { List<Neo4jError> errors = new LinkedList<>(); try { ensureActiveTransaction(); commit( statements, output, errors ); } catch ( InternalBeginTransactionError e ) { errors.add( e.toNeo4jError() ); } finally { output.errors( errors ); output.finish(); } } public void rollback( ExecutionResultSerializer output ) { List<Neo4jError> errors = new LinkedList<>(); try { ensureActiveTransaction(); rollback( errors ); } catch ( InternalBeginTransactionError e ) { errors.add( e.toNeo4jError() ); } finally { output.errors( errors ); output.finish(); } } public void forceRollback() throws TransactionFailureException { context.resumeSinceTransactionsAreStillThreadBound(); context.rollback(); } private void ensureActiveTransaction() throws InternalBeginTransactionError { if ( context == null ) { try { context = txManagerFacade.newTransaction(); } catch ( RuntimeException e ) { log.error( "Failed to start transaction.", e ); throw new InternalBeginTransactionError( e ); } } else { context.resumeSinceTransactionsAreStillThreadBound(); } } private void execute( StatementDeserializer statements, ExecutionResultSerializer output, List<Neo4jError> errors ) { executeStatements( statements, output, errors ); if ( Neo4jError.shouldRollBackOn( errors ) ) { rollback( errors ); } else { context.suspendSinceTransactionsAreStillThreadBound(); long lastActiveTimestamp = registry.release( id, this ); output.transactionStatus( lastActiveTimestamp ); } } private void commit( StatementDeserializer statements, ExecutionResultSerializer output, List<Neo4jError> errors ) { try { executeStatements( statements, output, errors ); if ( errors.isEmpty() ) { try { context.commit(); } catch ( Exception e ) { log.error( "Failed to commit transaction.", e ); errors.add( new Neo4jError( Status.Transaction.CouldNotCommit, e ) ); } } else { try { context.rollback(); } catch ( Exception e ) { log.error( "Failed to rollback transaction.", e ); errors.add( new Neo4jError( Status.Transaction.CouldNotRollback, e ) ); } } } finally { registry.forget( id ); } } private void rollback( List<Neo4jError> errors ) { try { context.rollback(); } catch ( Exception e ) { log.error( "Failed to rollback transaction.", e ); errors.add( new Neo4jError( Status.Transaction.CouldNotRollback, e ) ); } finally { registry.forget( id ); } } private void executeStatements( StatementDeserializer statements, ExecutionResultSerializer output, List<Neo4jError> errors ) { try { while ( statements.hasNext() ) { Statement statement = statements.next(); ExecutionResult result; try { result = engine.execute( statement.statement(), statement.parameters() ); output.statementResult( result, statement.includeStats(), statement.resultDataContents() ); } catch ( CypherException e ) { errors.add( new Neo4jError( e.status(), e ) ); break; } catch ( IOException e ) { errors.add( new Neo4jError( Status.Network.UnknownFailure, e ) ); break; } catch ( Exception e ) { errors.add( new Neo4jError( Status.Statement.ExecutionFailure, e ) ); break; } } Iterator<Neo4jError> deserializationErrors = statements.errors(); while ( deserializationErrors.hasNext() ) { errors.add( deserializationErrors.next() ); } } catch ( Exception e ) { errors.add( new Neo4jError( Status.General.UnknownFailure, e ) ); } } }
false
community_server_src_main_java_org_neo4j_server_rest_transactional_TransactionHandle.java
2,743
public class InvalidTransactionId extends TransactionLifecycleException { public InvalidTransactionId() { super( "Unrecognized transaction id. Transaction may have timed out and been rolled back." ); } @Override protected Status getStatusCode() { return Status.Transaction.UnknownId; } }
false
community_server_src_main_java_org_neo4j_server_rest_transactional_error_InvalidTransactionId.java
2,744
public class InternalBeginTransactionError extends TransactionLifecycleException { public InternalBeginTransactionError( RuntimeException cause ) { super( "Unable to begin transaction.", cause ); } @Override protected Status getStatusCode() { return Status.Transaction.CouldNotBegin; } }
false
community_server_src_main_java_org_neo4j_server_rest_transactional_error_InternalBeginTransactionError.java
2,745
public class ErrorDocumentationGeneratorTest { @Test public void tablesShouldFormatAsAsciiDoc() throws Exception { // Given ErrorDocumentationGenerator.Table table = new ErrorDocumentationGenerator.Table(); table.setCols( "COLS" ); table.setHeader( "A", "B" ); table.addRow( 1, 2 ); table.addRow( 3, 4 ); // When ByteArrayOutputStream buf = new ByteArrayOutputStream(); PrintStream out = new PrintStream( buf, false, "UTF-8" ); table.print( out ); out.flush(); // Then String result = buf.toString( "UTF-8" ); String n = System.lineSeparator(); String expected = "[options=\"header\", cols=\"COLS\"]" + n + "|===" + n + "|A |B " + n + "|1 |2 " + n + "|3 |4 " + n + "|===" + n; assertThat( result, is(equalTo( expected )) ); } @Test public void shouldGenerateTableOfClassifications() throws Exception { // Given ErrorDocumentationGenerator gen = new ErrorDocumentationGenerator(); // When ErrorDocumentationGenerator.Table table = gen.generateClassificationDocs(); // Then ByteArrayOutputStream buf = new ByteArrayOutputStream(); table.print( new PrintStream( buf, true, "UTF-8" ) ); String actual = buf.toString( "UTF-8" ); // More or less randomly chosen bits of text that should be in the output: assertThat( actual, stringContainsInOrder( asList( "DatabaseError", "Rollback" ) ) ); } @Test public void shouldGenerateTableOfStatusCodes() throws Exception { // Given ErrorDocumentationGenerator gen = new ErrorDocumentationGenerator(); // When ErrorDocumentationGenerator.Table table = gen.generateStatusCodeDocs(); // Then ByteArrayOutputStream buf = new ByteArrayOutputStream(); table.print( new PrintStream( buf, true, "UTF-8" ) ); String actual = buf.toString( "UTF-8" ); // More or less randomly chosen bits of text that should be in the output: assertThat( actual, stringContainsInOrder( asList( "UnknownFailure", "An unknown failure occurred" ) ) ); } }
false
community_server_src_test_java_org_neo4j_server_rest_transactional_error_ErrorDocumentationGeneratorTest.java
2,746
public static class Table { private String cols; private String[] header; private List<Object[]> rows = new ArrayList<>(); public void setCols( String cols ) { this.cols = cols; } public void setHeader( String... header ) { this.header = header; } public void addRow( Object... xs ) { rows.add(xs); } public void print( PrintStream out ) { out.printf( "[options=\"header\", cols=\"%s\"]%n", cols ); out.printf( "|===%n" ); for( String columnHeader : header ) { out.printf( "|%s ", columnHeader ); } out.printf( "%n" ); for( Object[] row : rows ) { for( Object cell : row ) { out.printf( "|%s ", cell ); } out.printf( "%n" ); } out.printf( "|===%n" ); } }
false
community_server_src_main_java_org_neo4j_server_rest_transactional_error_ErrorDocumentationGenerator.java
2,747
public class ErrorDocumentationGenerator { public static void main( String[] args ) throws Exception { File baseDir = getBaseDirectory( args ); ErrorDocumentationGenerator generator = new ErrorDocumentationGenerator(); try { generateDocumentation( generator.generateClassificationDocs(), new File( baseDir, "status-code-classifications.asccidoc" ), "status code classification" ); generateDocumentation( generator.generateStatusCodeDocs(), new File( baseDir, "status-code-codes.asccidoc" ), "status code statuses"); } catch ( Exception e ) { // Send it to standard out, so we can see it through the Maven build. e.printStackTrace( System.out ); System.out.flush(); System.exit( 1 ); } } private static File getBaseDirectory( String[] args ) { File baseDir = null; if(args.length == 1) { baseDir = new File(args[0]); } else { System.out.println("Usage: ErrorDocumentationGenerator [output folder]"); System.exit(0); } return baseDir; } private static void generateDocumentation( Table table, File file, String description ) throws Exception { System.out.printf( "Saving %s docs in '%s'.%n", description, file.getAbsolutePath() ); file.getParentFile().mkdirs(); try ( PrintStream out = new PrintStream( file, "UTF-8" ) ) { table.print( out ); } } public Table generateClassificationDocs() { Table table = new Table(); table.setCols( "<1m,<3,<1" ); table.setHeader( "Classification", "Description", "Effect on transaction" ); for ( Status.Classification classification : Status.Classification.class.getEnumConstants() ) { table.addRow( classificationAsRow( classification ) ); } return table; } private Object[] classificationAsRow( Status.Classification classification ) { // TODO fail on missing description String description = classification.description().length() > 0 ? classification.description() : "No description available."; String txEffect = classification.rollbackTransaction() ? "Rollback" : "None"; return new Object[] { classification.name(), description, txEffect }; } public Table generateStatusCodeDocs() { Table table = new Table(); table.setCols( "<1m,<1" ); table.setHeader( "Status Code", "Description" ); TreeMap<String, Status.Code> sortedStatuses = sortedStatusCodes(); for ( String code : sortedStatuses.keySet() ) { Status.Code statusCode = sortedStatuses.get( code ); table.addRow( codeAsTableRow( statusCode ) ); } return table; } private Object[] codeAsTableRow( Status.Code code ) { // TODO fail on missing description String description = code.description().length() > 0 ? code.description() : "No description available."; return new Object[] { code.serialize(), description }; } private TreeMap<String, Status.Code> sortedStatusCodes() { TreeMap<String, Status.Code> sortedStatuses = new TreeMap<>(); for ( Status status : Status.Code.all() ) { sortedStatuses.put( status.code().serialize(), status.code() ); } return sortedStatuses; } public static class Table { private String cols; private String[] header; private List<Object[]> rows = new ArrayList<>(); public void setCols( String cols ) { this.cols = cols; } public void setHeader( String... header ) { this.header = header; } public void addRow( Object... xs ) { rows.add(xs); } public void print( PrintStream out ) { out.printf( "[options=\"header\", cols=\"%s\"]%n", cols ); out.printf( "|===%n" ); for( String columnHeader : header ) { out.printf( "|%s ", columnHeader ); } out.printf( "%n" ); for( Object[] row : rows ) { for( Object cell : row ) { out.printf( "|%s ", cell ); } out.printf( "%n" ); } out.printf( "|===%n" ); } } }
false
community_server_src_main_java_org_neo4j_server_rest_transactional_error_ErrorDocumentationGenerator.java
2,748
class TransitionalTxManagementKernelTransaction { private final TransactionManager txManager; private Transaction suspendedTransaction; public TransitionalTxManagementKernelTransaction( TransactionManager txManager ) { this.txManager = txManager; } public void suspendSinceTransactionsAreStillThreadBound() { try { assert suspendedTransaction == null : "Can't suspend the transaction if it already is suspended."; suspendedTransaction = txManager.suspend(); } catch ( SystemException e ) { throw new RuntimeException( e ); } } public void resumeSinceTransactionsAreStillThreadBound() { try { assert suspendedTransaction != null : "Can't suspend the transaction if it has not first been suspended."; txManager.resume( suspendedTransaction ); suspendedTransaction = null; } catch ( InvalidTransactionException | SystemException e ) { throw new RuntimeException( e ); } } public void rollback() { try { txManager.rollback(); } catch ( SystemException e ) { throw new RuntimeException( e ); } } public void commit() { try { txManager.commit(); } catch ( RollbackException | HeuristicMixedException | HeuristicRollbackException | SystemException e ) { throw new RuntimeException( e ); } } }
false
community_server_src_main_java_org_neo4j_server_rest_transactional_TransitionalTxManagementKernelTransaction.java
2,749
public class TransitionalPeriodTransactionMessContainer { private final GraphDatabaseAPI db; private final TransactionManager txManager; public TransitionalPeriodTransactionMessContainer( GraphDatabaseAPI db ) { this.db = db; this.txManager = db.getDependencyResolver().resolveDependency( TransactionManager.class ); } public TransitionalTxManagementKernelTransaction newTransaction() { db.beginTx(); // Get and use the TransactionContext created in db.beginTx(). The role of creating // TransactionContexts will be reversed soonish. return new TransitionalTxManagementKernelTransaction( txManager ); } }
false
community_server_src_main_java_org_neo4j_server_rest_transactional_TransitionalPeriodTransactionMessContainer.java
2,750
{ Transaction transaction; @Override public void onRepresentationStartWriting() { transaction = database.getGraph().beginTx(); } @Override public void onRepresentationWritten() { // doesn't need to commit } @Override public void onRepresentationFinal() { if ( transaction != null ) { transaction.close(); } } } );
false
community_server_src_main_java_org_neo4j_server_rest_transactional_TransactionalRequestDispatcher.java
2,751
{ @Override public void onRepresentationStartWriting() { // do nothing } @Override public void onRepresentationWritten() { // doesn't need to commit } @Override public void onRepresentationFinal() { transaction.close(); } } );
false
community_server_src_main_java_org_neo4j_server_rest_transactional_TransactionalRequestDispatcher.java
2,752
public class TransactionalRequestDispatcher implements RequestDispatcher { private final Database database; private final RequestDispatcher requestDispatcher; public TransactionalRequestDispatcher( Database database, RequestDispatcher requestDispatcher ) { this.database = database; this.requestDispatcher = requestDispatcher; } @Override public void dispatch( Object o, final HttpContext httpContext ) { RepresentationWriteHandler representationWriteHandler = DO_NOTHING; if ( o instanceof RestfulGraphDatabase ) { RestfulGraphDatabase restfulGraphDatabase = (RestfulGraphDatabase) o; final Transaction transaction = database.getGraph().beginTx(); restfulGraphDatabase.getOutputFormat().setRepresentationWriteHandler( representationWriteHandler = new CommitOnSuccessfulStatusCodeRepresentationWriteHandler( httpContext, transaction )); } else if ( o instanceof BatchOperationService ) { BatchOperationService batchOperationService = (BatchOperationService) o; final Transaction transaction = database.getGraph().beginTx(); batchOperationService.setRepresentationWriteHandler( representationWriteHandler = new CommitOnSuccessfulStatusCodeRepresentationWriteHandler( httpContext, transaction ) ); } else if ( o instanceof CypherService ) { CypherService cypherService = (CypherService) o; final Transaction transaction = database.getGraph().beginTx(); cypherService.getOutputFormat().setRepresentationWriteHandler( representationWriteHandler = new CommitOnSuccessfulStatusCodeRepresentationWriteHandler( httpContext, transaction ) ); } else if ( o instanceof DatabaseMetadataService ) { DatabaseMetadataService databaseMetadataService = (DatabaseMetadataService) o; final Transaction transaction = database.getGraph().beginTx(); databaseMetadataService.setRepresentationWriteHandler( representationWriteHandler = new RepresentationWriteHandler() { @Override public void onRepresentationStartWriting() { // do nothing } @Override public void onRepresentationWritten() { // doesn't need to commit } @Override public void onRepresentationFinal() { transaction.close(); } } ); } else if ( o instanceof ExtensionService ) { ExtensionService extensionService = (ExtensionService) o; extensionService.getOutputFormat().setRepresentationWriteHandler( representationWriteHandler = new RepresentationWriteHandler() { Transaction transaction; @Override public void onRepresentationStartWriting() { transaction = database.getGraph().beginTx(); } @Override public void onRepresentationWritten() { // doesn't need to commit } @Override public void onRepresentationFinal() { if ( transaction != null ) { transaction.close(); } } } ); } try { requestDispatcher.dispatch( o, httpContext ); } catch ( RuntimeException e ) { representationWriteHandler.onRepresentationFinal(); throw e; } } }
false
community_server_src_main_java_org_neo4j_server_rest_transactional_TransactionalRequestDispatcher.java
2,753
{ @Override protected boolean matchesSafely( Iterable<Neo4jError> item ) { Set<Status> actualErrorCodes = new HashSet<>(); for ( Neo4jError neo4jError : item ) { actualErrorCodes.add( neo4jError.status() ); } return expectedErrorsCodes.equals( actualErrorCodes ); } @Override public void describeTo( Description description ) { description.appendText( "Errors with set of codes" ).appendValue( expectedErrorsCodes ); } };
false
community_server_src_test_java_org_neo4j_server_rest_transactional_TransactionHandleTest.java
2,754
{ @Override public URI txUri( long id ) { return URI.create( "transaction/" + id ); } @Override public URI txCommitUri( long id ) { return URI.create( "transaction/" + id + "/commit" ); } };
false
community_server_src_test_java_org_neo4j_server_rest_transactional_TransactionHandleTest.java
2,755
{ @Override public Object answer( InvocationOnMock invocationOnMock ) throws Throwable { throw new Exception("BOO"); } });
false
community_server_src_test_java_org_neo4j_server_rest_transactional_TransactionHandleTest.java
2,756
public class TransactionHandleTest { @Test public void shouldExecuteStatements() throws Exception { // given TransitionalPeriodTransactionMessContainer kernel = mockKernel(); ExecutionEngine executionEngine = mock( ExecutionEngine.class ); ExecutionResult executionResult = mock( ExecutionResult.class ); when( executionEngine.execute( "query", map() ) ).thenReturn( executionResult ); TransactionRegistry registry = mock( TransactionRegistry.class ); when( registry.begin() ).thenReturn( 1337l ); TransactionHandle handle = new TransactionHandle( kernel, executionEngine, registry, uriScheme, StringLogger.DEV_NULL ); ExecutionResultSerializer output = mock( ExecutionResultSerializer.class ); // when handle.execute( statements( new Statement( "query", map(), false, (ResultDataContent[])null ) ), output ); // then verify( executionEngine ).execute( "query", map() ); InOrder outputOrder = inOrder( output ); outputOrder.verify( output ).transactionCommitUri( uriScheme.txCommitUri( 1337 ) ); outputOrder.verify( output ).statementResult( executionResult, false, (ResultDataContent[])null ); outputOrder.verify( output ).transactionStatus( anyLong() ); outputOrder.verify( output ).errors( argThat( hasNoErrors() ) ); outputOrder.verify( output ).finish(); verifyNoMoreInteractions( output ); } @Test public void shouldSuspendTransactionAndReleaseForOtherRequestsAfterExecutingStatements() throws Exception { // given TransitionalPeriodTransactionMessContainer kernel = mockKernel(); TransitionalTxManagementKernelTransaction transactionContext = kernel.newTransaction(); TransactionRegistry registry = mock( TransactionRegistry.class ); when( registry.begin() ).thenReturn( 1337l ); ExecutionEngine engine = mock( ExecutionEngine.class ); ExecutionResult executionResult = mock( ExecutionResult.class ); when( engine.execute( "query", map() ) ).thenReturn( executionResult ); TransactionHandle handle = new TransactionHandle( kernel, engine, registry, uriScheme, StringLogger.DEV_NULL ); ExecutionResultSerializer output = mock( ExecutionResultSerializer.class ); // when handle.execute( statements( new Statement( "query", map(), false, (ResultDataContent[]) null ) ), output ); // then InOrder transactionOrder = inOrder( transactionContext, registry ); transactionOrder.verify( transactionContext ).suspendSinceTransactionsAreStillThreadBound(); transactionOrder.verify( registry ).release( 1337l, handle ); InOrder outputOrder = inOrder( output ); outputOrder.verify( output ).transactionCommitUri( uriScheme.txCommitUri( 1337 ) ); outputOrder.verify( output ).statementResult( executionResult, false, (ResultDataContent[])null ); outputOrder.verify( output ).transactionStatus( anyLong() ); outputOrder.verify( output ).errors( argThat( hasNoErrors() ) ); outputOrder.verify( output ).finish(); verifyNoMoreInteractions( output ); } @Test public void shouldResumeTransactionWhenExecutingStatementsOnSecondRequest() throws Exception { // given TransitionalPeriodTransactionMessContainer kernel = mockKernel(); TransitionalTxManagementKernelTransaction transactionContext = kernel.newTransaction(); TransactionRegistry registry = mock( TransactionRegistry.class ); when( registry.begin() ).thenReturn( 1337l ); ExecutionEngine executionEngine = mock( ExecutionEngine.class ); TransactionHandle handle = new TransactionHandle( kernel, executionEngine, registry, uriScheme, StringLogger.DEV_NULL ); ExecutionResultSerializer output = mock( ExecutionResultSerializer.class ); handle.execute( statements( new Statement( "query", map(), false, (ResultDataContent[])null ) ), output ); reset( transactionContext, registry, executionEngine, output ); ExecutionResult executionResult = mock( ExecutionResult.class ); when( executionEngine.execute( "query", map() ) ).thenReturn( executionResult ); // when handle.execute( statements( new Statement( "query", map(), false, (ResultDataContent[])null ) ), output ); // then InOrder order = inOrder( transactionContext, registry, executionEngine ); order.verify( transactionContext ).resumeSinceTransactionsAreStillThreadBound(); order.verify( executionEngine ).execute( "query", map() ); order.verify( transactionContext ).suspendSinceTransactionsAreStillThreadBound(); order.verify( registry ).release( 1337l, handle ); InOrder outputOrder = inOrder( output ); outputOrder.verify( output ).transactionCommitUri( uriScheme.txCommitUri( 1337 ) ); outputOrder.verify( output ).statementResult( executionResult, false, (ResultDataContent[])null ); outputOrder.verify( output ).transactionStatus( anyLong() ); outputOrder.verify( output ).errors( argThat( hasNoErrors() ) ); outputOrder.verify( output ).finish(); verifyNoMoreInteractions( output ); } @Test public void shouldCommitTransactionAndTellRegistryToForgetItsHandle() throws Exception { // given TransitionalPeriodTransactionMessContainer kernel = mockKernel(); TransitionalTxManagementKernelTransaction transactionContext = kernel.newTransaction(); TransactionRegistry registry = mock( TransactionRegistry.class ); when( registry.begin() ).thenReturn( 1337l ); ExecutionEngine engine = mock( ExecutionEngine.class ); ExecutionResult result = mock( ExecutionResult.class ); when( engine.execute( "query", map() ) ).thenReturn( result ); TransactionHandle handle = new TransactionHandle( kernel, engine, registry, uriScheme, StringLogger.DEV_NULL ); ExecutionResultSerializer output = mock( ExecutionResultSerializer.class ); // when handle.commit( statements( new Statement( "query", map(), false, (ResultDataContent[]) null ) ), output ); // then InOrder transactionOrder = inOrder( transactionContext, registry ); transactionOrder.verify( transactionContext ).commit(); transactionOrder.verify( registry ).forget( 1337l ); InOrder outputOrder = inOrder( output ); outputOrder.verify( output ).statementResult( result, false, (ResultDataContent[])null ); outputOrder.verify( output ).errors( argThat( hasNoErrors() ) ); outputOrder.verify( output ).finish(); verifyNoMoreInteractions( output ); } @Test public void shouldRollbackTransactionAndTellRegistryToForgetItsHandle() throws Exception { // given TransitionalPeriodTransactionMessContainer kernel = mockKernel(); TransitionalTxManagementKernelTransaction transactionContext = kernel.newTransaction(); TransactionRegistry registry = mock( TransactionRegistry.class ); when( registry.begin() ).thenReturn( 1337l ); TransactionHandle handle = new TransactionHandle( kernel, mock( ExecutionEngine.class ), registry, uriScheme, StringLogger.DEV_NULL ); ExecutionResultSerializer output = mock( ExecutionResultSerializer.class ); // when handle.rollback( output ); // then InOrder transactionOrder = inOrder( transactionContext, registry ); transactionOrder.verify( transactionContext ).rollback(); transactionOrder.verify( registry ).forget( 1337l ); InOrder outputOrder = inOrder( output ); outputOrder.verify( output ).errors( argThat( hasNoErrors() ) ); outputOrder.verify( output ).finish(); verifyNoMoreInteractions( output ); } @Test public void shouldCreateTransactionContextOnlyWhenFirstNeeded() throws Exception { // given TransitionalPeriodTransactionMessContainer kernel = mockKernel(); ExecutionResultSerializer output = mock( ExecutionResultSerializer.class ); TransactionRegistry registry = mock( TransactionRegistry.class ); when( registry.begin() ).thenReturn( 1337l ); // when ExecutionEngine engine = mock( ExecutionEngine.class ); ExecutionResult executionResult = mock( ExecutionResult.class ); when( engine.execute( "query", map() ) ).thenReturn( executionResult ); TransactionHandle handle = new TransactionHandle( kernel, engine, registry, uriScheme, StringLogger.DEV_NULL ); // then verifyZeroInteractions( kernel ); // when handle.execute( statements( new Statement( "query", map(), false, (ResultDataContent[])null ) ), output ); // then verify( kernel ).newTransaction(); InOrder outputOrder = inOrder( output ); outputOrder.verify( output ).transactionCommitUri( uriScheme.txCommitUri( 1337 ) ); outputOrder.verify( output ).statementResult( executionResult, false, (ResultDataContent[])null ); outputOrder.verify( output ).transactionStatus( anyLong() ); outputOrder.verify( output ).errors( argThat( hasNoErrors() ) ); outputOrder.verify( output ).finish(); verifyNoMoreInteractions( output ); } @Test public void shouldRollbackTransactionIfExecutionErrorOccurs() throws Exception { // given TransitionalPeriodTransactionMessContainer kernel = mockKernel(); TransitionalTxManagementKernelTransaction transactionContext = kernel.newTransaction(); TransactionRegistry registry = mock( TransactionRegistry.class ); when( registry.begin() ).thenReturn( 1337l ); ExecutionEngine executionEngine = mock( ExecutionEngine.class ); when( executionEngine.execute( "query", map() ) ).thenThrow( new NullPointerException() ); TransactionHandle handle = new TransactionHandle( kernel, executionEngine, registry, uriScheme, StringLogger.DEV_NULL ); ExecutionResultSerializer output = mock( ExecutionResultSerializer.class ); // when handle.execute( statements( new Statement( "query", map(), false, (ResultDataContent[])null ) ), output ); // then verify( transactionContext ).rollback(); verify( registry ).forget( 1337l ); InOrder outputOrder = inOrder( output ); outputOrder.verify( output ).transactionCommitUri( uriScheme.txCommitUri( 1337 ) ); outputOrder.verify( output ).errors( argThat( hasErrors( Status.Statement.ExecutionFailure ) ) ); outputOrder.verify( output ).finish(); verifyNoMoreInteractions( output ); } @Test public void shouldLogMessageIfCommitErrorOccurs() throws Exception { // given TransitionalPeriodTransactionMessContainer kernel = mockKernel(); TransitionalTxManagementKernelTransaction transactionContext = kernel.newTransaction(); doThrow( new NullPointerException() ).when( transactionContext ).commit(); StringLogger log = mock( StringLogger.class ); TransactionRegistry registry = mock( TransactionRegistry.class ); when( registry.begin() ).thenReturn( 1337l ); ExecutionEngine engine = mock( ExecutionEngine.class ); ExecutionResult executionResult = mock( ExecutionResult.class ); when( engine.execute( "query", map() ) ).thenReturn( executionResult ); TransactionHandle handle = new TransactionHandle( kernel, engine, registry, uriScheme, log ); ExecutionResultSerializer output = mock( ExecutionResultSerializer.class ); // when handle.commit( statements( new Statement( "query", map(), false, (ResultDataContent[])null ) ), output ); // then verify( log ).error( eq( "Failed to commit transaction." ), any( NullPointerException.class ) ); verify( registry ).forget( 1337l ); InOrder outputOrder = inOrder( output ); outputOrder.verify( output ).statementResult( executionResult, false, (ResultDataContent[])null ); outputOrder.verify( output ).errors( argThat( hasErrors( Status.Transaction.CouldNotCommit ) ) ); outputOrder.verify( output ).finish(); verifyNoMoreInteractions( output ); } @Test public void shouldLogMessageIfCypherSyntaxErrorOccurs() throws Exception { // given TransitionalPeriodTransactionMessContainer kernel = mockKernel(); ExecutionEngine executionEngine = mock( ExecutionEngine.class ); when( executionEngine.execute( "matsch (n) return n", map() ) ).thenThrow( new SyntaxException( "did you mean MATCH?" ) ); StringLogger log = mock( StringLogger.class ); TransactionRegistry registry = mock( TransactionRegistry.class ); when( registry.begin() ).thenReturn( 1337l ); TransactionHandle handle = new TransactionHandle( kernel, executionEngine, registry, uriScheme, log ); ExecutionResultSerializer output = mock( ExecutionResultSerializer.class ); // when handle.commit( statements( new Statement( "matsch (n) return n", map(), false, (ResultDataContent[])null ) ), output ); // then verify( registry ).forget( 1337l ); InOrder outputOrder = inOrder( output ); outputOrder.verify( output ).errors( argThat( hasErrors( Status.Statement.InvalidSyntax ) ) ); outputOrder.verify( output ).finish(); verifyNoMoreInteractions( output ); } @Test public void shouldHandleExecutionEngineThrowingUndeclaredCheckedExceptions() throws Exception { // given ExecutionEngine executionEngine = mock( ExecutionEngine.class ); when( executionEngine.execute( "match (n) return n", map() ) ).thenAnswer( new Answer() { @Override public Object answer( InvocationOnMock invocationOnMock ) throws Throwable { throw new Exception("BOO"); } }); TransactionRegistry registry = mock( TransactionRegistry.class ); when( registry.begin() ).thenReturn( 1337l ); TransactionHandle handle = new TransactionHandle( mockKernel(), executionEngine, registry, uriScheme, mock( StringLogger.class ) ); ExecutionResultSerializer output = mock( ExecutionResultSerializer.class ); // when handle.commit( statements( new Statement( "match (n) return n", map(), false, (ResultDataContent[])null ) ), output ); // then verify( registry ).forget( 1337l ); InOrder outputOrder = inOrder( output ); outputOrder.verify( output ).errors( argThat( hasErrors( Status.Statement.ExecutionFailure ) ) ); outputOrder.verify( output ).finish(); verifyNoMoreInteractions( output ); } private static final TransactionUriScheme uriScheme = new TransactionUriScheme() { @Override public URI txUri( long id ) { return URI.create( "transaction/" + id ); } @Override public URI txCommitUri( long id ) { return URI.create( "transaction/" + id + "/commit" ); } }; private TransitionalPeriodTransactionMessContainer mockKernel() { TransitionalTxManagementKernelTransaction context = mock( TransitionalTxManagementKernelTransaction.class ); TransitionalPeriodTransactionMessContainer kernel = mock( TransitionalPeriodTransactionMessContainer.class ); when( kernel.newTransaction() ).thenReturn( context ); return kernel; } private static Matcher<Iterable<Neo4jError>> hasNoErrors() { return hasErrors(); } private static Matcher<Iterable<Neo4jError>> hasErrors( Status... codes ) { final Set<Status> expectedErrorsCodes = new HashSet<>( asList( codes ) ); return new TypeSafeMatcher<Iterable<Neo4jError>>() { @Override protected boolean matchesSafely( Iterable<Neo4jError> item ) { Set<Status> actualErrorCodes = new HashSet<>(); for ( Neo4jError neo4jError : item ) { actualErrorCodes.add( neo4jError.status() ); } return expectedErrorsCodes.equals( actualErrorCodes ); } @Override public void describeTo( Description description ) { description.appendText( "Errors with set of codes" ).appendValue( expectedErrorsCodes ); } }; } }
false
community_server_src_test_java_org_neo4j_server_rest_transactional_TransactionHandleTest.java
2,757
public class TransactionHandleRegistryTest { @Test public void shouldGenerateTransactionId() throws Exception { // given TestLogger log = new TestLogger(); TransactionHandleRegistry registry = new TransactionHandleRegistry( new FakeClock(), 0, log ); // when long id1 = registry.begin(); long id2 = registry.begin(); // then assertNotEquals( id1, id2 ); log.assertNoLoggingOccurred(); } @Test public void shouldStoreSuspendedTransaction() throws Exception { // Given TestLogger log = new TestLogger(); TransactionHandleRegistry registry = new TransactionHandleRegistry( new FakeClock(), 0, log ); TransactionHandle handle = mock( TransactionHandle.class ); long id = registry.begin(); // When registry.release( id, handle ); TransactionHandle acquiredHandle = registry.acquire( id ); // Then assertSame( handle, acquiredHandle ); log.assertNoLoggingOccurred(); } @Test public void acquiringATransactionThatHasAlreadyBeenAcquiredShouldThrowInvalidConcurrentTransactionAccess() throws Exception { // Given TestLogger log = new TestLogger(); TransactionHandleRegistry registry = new TransactionHandleRegistry( new FakeClock(), 0, log ); TransactionHandle handle = mock( TransactionHandle.class ); long id = registry.begin(); registry.release( id, handle ); registry.acquire( id ); // When try { registry.acquire( id ); fail( "Should have thrown exception" ); } catch ( InvalidConcurrentTransactionAccess e ) { // expected } // then log.assertNoLoggingOccurred(); } @Test public void acquiringANonExistentTransactionShouldThrowErrorInvalidTransactionId() throws Exception { // Given TestLogger log = new TestLogger(); TransactionHandleRegistry registry = new TransactionHandleRegistry( new FakeClock(), 0, log ); long madeUpTransactionId = 1337; // When try { registry.acquire( madeUpTransactionId ); fail( "Should have thrown exception" ); } catch ( InvalidTransactionId e ) { // expected } // then log.assertNoLoggingOccurred(); } @Test public void transactionsShouldBeEvictedWhenUnusedLongerThanTimeout() throws Exception { // Given FakeClock clock = new FakeClock(); TestLogger log = new TestLogger(); TransactionHandleRegistry registry = new TransactionHandleRegistry( clock, 0, log ); TransactionHandle oldTx = mock( TransactionHandle.class ); TransactionHandle newTx = mock( TransactionHandle.class ); long txId1 = registry.begin(); long txId2 = registry.begin(); // And given one transaction was stored one minute ago, and another was stored just now registry.release( txId1, oldTx ); clock.forward( 1, TimeUnit.MINUTES ); registry.release( txId2, newTx ); // When registry.rollbackSuspendedTransactionsIdleSince( clock.currentTimeMillis() - 1000 ); // Then assertThat( registry.acquire( txId2 ), equalTo( newTx ) ); // And then the other should have been evicted try { registry.acquire( txId1 ); fail( "Should have thrown exception" ); } catch ( InvalidTransactionId e ) { // ok } log.assertExactly( info( "Transaction with id 1 has been automatically rolled back." ) ); } @Test public void expiryTimeShouldBeSetToCurrentTimePlusTimeout() throws Exception { // Given TestLogger log = new TestLogger(); FakeClock clock = new FakeClock(); int timeoutLength = 123; TransactionHandleRegistry registry = new TransactionHandleRegistry( clock, timeoutLength, log ); TransactionHandle handle = mock( TransactionHandle.class ); long id = registry.begin(); // When long timesOutAt = registry.release( id, handle ); // Then assertThat( timesOutAt, equalTo( clock.currentTimeMillis() + timeoutLength ) ); // And when clock.forward( 1337, TimeUnit.MILLISECONDS ); registry.acquire( id ); timesOutAt = registry.release( id, handle ); // Then assertThat( timesOutAt, equalTo( clock.currentTimeMillis() + timeoutLength ) ); } }
false
community_server_src_test_java_org_neo4j_server_rest_transactional_TransactionHandleRegistryTest.java
2,758
private static abstract class TransactionMarker { abstract SuspendedTransaction getTransaction() throws InvalidConcurrentTransactionAccess; abstract boolean isSuspended(); }
false
community_server_src_main_java_org_neo4j_server_rest_transactional_TransactionHandleRegistry.java
2,759
private class SuspendedTransaction extends TransactionMarker { final TransactionHandle transactionHandle; final long lastActiveTimestamp; private SuspendedTransaction( TransactionHandle transactionHandle ) { this.transactionHandle = transactionHandle; this.lastActiveTimestamp = clock.currentTimeMillis(); } @Override SuspendedTransaction getTransaction() throws InvalidConcurrentTransactionAccess { return this; } @Override boolean isSuspended() { return true; } public long getLastActiveTimestamp() { return lastActiveTimestamp; } }
false
community_server_src_main_java_org_neo4j_server_rest_transactional_TransactionHandleRegistry.java
2,760
private static class ActiveTransaction extends TransactionMarker { public static final ActiveTransaction INSTANCE = new ActiveTransaction(); @Override SuspendedTransaction getTransaction() throws InvalidConcurrentTransactionAccess { throw new InvalidConcurrentTransactionAccess(); } @Override boolean isSuspended() { return false; } }
false
community_server_src_main_java_org_neo4j_server_rest_transactional_TransactionHandleRegistry.java
2,761
{ @Override public boolean accept( TransactionMarker item ) { try { SuspendedTransaction transaction = item.getTransaction(); return transaction.lastActiveTimestamp < oldestLastActiveTime; } catch ( InvalidConcurrentTransactionAccess concurrentTransactionAccessError ) { throw new RuntimeException( concurrentTransactionAccessError ); } } } );
false
community_server_src_main_java_org_neo4j_server_rest_transactional_TransactionHandleRegistry.java
2,762
public class TransactionHandleRegistry implements TransactionRegistry { private final AtomicLong idGenerator = new AtomicLong( 0l ); private final ConcurrentHashMap<Long, TransactionMarker> registry = new ConcurrentHashMap<>( 64 ); private final Clock clock; private final StringLogger log; private final long timeoutMillis; public TransactionHandleRegistry( Clock clock, long timeoutMillis, StringLogger log ) { this.clock = clock; this.timeoutMillis = timeoutMillis; this.log = log; } private static abstract class TransactionMarker { abstract SuspendedTransaction getTransaction() throws InvalidConcurrentTransactionAccess; abstract boolean isSuspended(); } private static class ActiveTransaction extends TransactionMarker { public static final ActiveTransaction INSTANCE = new ActiveTransaction(); @Override SuspendedTransaction getTransaction() throws InvalidConcurrentTransactionAccess { throw new InvalidConcurrentTransactionAccess(); } @Override boolean isSuspended() { return false; } } private class SuspendedTransaction extends TransactionMarker { final TransactionHandle transactionHandle; final long lastActiveTimestamp; private SuspendedTransaction( TransactionHandle transactionHandle ) { this.transactionHandle = transactionHandle; this.lastActiveTimestamp = clock.currentTimeMillis(); } @Override SuspendedTransaction getTransaction() throws InvalidConcurrentTransactionAccess { return this; } @Override boolean isSuspended() { return true; } public long getLastActiveTimestamp() { return lastActiveTimestamp; } } @Override public long begin() { long id = idGenerator.incrementAndGet(); if ( null == registry.putIfAbsent( id, ActiveTransaction.INSTANCE ) ) { return id; } else { throw new IllegalStateException( "Attempt to begin transaction for id that was already registered" ); } } @Override public long release( long id, TransactionHandle transactionHandle ) { TransactionMarker marker = registry.get( id ); if ( null == marker ) { throw new IllegalStateException( "Trying to suspend unregistered transaction" ); } if ( marker.isSuspended() ) { throw new IllegalStateException( "Trying to suspend transaction that was already suspended" ); } SuspendedTransaction suspendedTx = new SuspendedTransaction( transactionHandle ); if ( !registry.replace( id, marker, suspendedTx ) ) { throw new IllegalStateException( "Trying to suspend transaction that has been concurrently suspended" ); } return computeNewExpiryTime( suspendedTx.getLastActiveTimestamp() ); } private long computeNewExpiryTime( long lastActiveTimestamp ) { return lastActiveTimestamp + timeoutMillis; } @Override public TransactionHandle acquire( long id ) throws TransactionLifecycleException { TransactionMarker marker = registry.get( id ); if ( null == marker ) { throw new InvalidTransactionId(); } if ( !marker.isSuspended() ) { throw new InvalidConcurrentTransactionAccess(); } SuspendedTransaction transaction = marker.getTransaction(); if ( registry.replace( id, marker, ActiveTransaction.INSTANCE ) ) { return transaction.transactionHandle; } else { throw new InvalidConcurrentTransactionAccess(); } } @Override public void forget( long id ) { TransactionMarker marker = registry.get( id ); if ( null == marker ) { throw new IllegalStateException( "Could not finish unregistered transaction" ); } if ( marker.isSuspended() ) { throw new IllegalStateException( "Cannot finish suspended registered transaction" ); } if ( !registry.remove( id, marker ) ) { throw new IllegalStateException( "Trying to finish transaction that has been concurrently finished or suspended" ); } } @Override public void rollbackAllSuspendedTransactions() { rollbackSuspended( Predicates.<TransactionMarker>TRUE() ); } public void rollbackSuspendedTransactionsIdleSince( final long oldestLastActiveTime ) { rollbackSuspended( new Predicate<TransactionMarker>() { @Override public boolean accept( TransactionMarker item ) { try { SuspendedTransaction transaction = item.getTransaction(); return transaction.lastActiveTimestamp < oldestLastActiveTime; } catch ( InvalidConcurrentTransactionAccess concurrentTransactionAccessError ) { throw new RuntimeException( concurrentTransactionAccessError ); } } } ); } private void rollbackSuspended( Predicate<TransactionMarker> predicate ) { Set<Long> candidateTransactionIdsToRollback = new HashSet<Long>(); for ( Map.Entry<Long, TransactionMarker> entry : registry.entrySet() ) { TransactionMarker marker = entry.getValue(); if (marker.isSuspended() && predicate.accept(marker)) { candidateTransactionIdsToRollback.add( entry.getKey() ); } } for ( long id : candidateTransactionIdsToRollback ) { TransactionHandle handle; try { handle = acquire( id ); } catch ( TransactionLifecycleException invalidTransactionId ) { // Allow this - someone snatched the transaction from under our feet, continue; } try { handle.forceRollback(); log.info( format( "Transaction with id %d has been automatically rolled back.", id ) ); } catch ( TransactionFailureException e ) { log.error( format( "Transaction with id %d failed to roll back.", id ), e ); } finally { forget( id ); } } } }
false
community_server_src_main_java_org_neo4j_server_rest_transactional_TransactionHandleRegistry.java
2,763
public class InvalidConcurrentTransactionAccess extends TransactionLifecycleException { public InvalidConcurrentTransactionAccess() { super( "The requested transaction is being used concurrently by another request." ); } @Override protected Status getStatusCode() { return Status.Transaction.ConcurrentRequest; } }
false
community_server_src_main_java_org_neo4j_server_rest_transactional_error_InvalidConcurrentTransactionAccess.java
2,764
public class Neo4jError { private final Status status; private final Throwable cause; public Neo4jError( Status status, Throwable cause ) { if ( status == null ) throw new IllegalArgumentException( "statusCode must not be null" ); if ( cause == null ) throw new IllegalArgumentException( "cause must not be null" ); this.status = status; this.cause = cause; } public Status status() { return status; } public String getMessage() { return cause.getMessage(); } public boolean shouldSerializeStackTrace() { switch(status.code().classification()) { case ClientError: return false; default: return true; } } public String getStackTraceAsString() { StringWriter stringWriter = new StringWriter( ); PrintWriter printWriter = new PrintWriter( stringWriter ); cause.printStackTrace( printWriter ); return stringWriter.toString(); } public static boolean shouldRollBackOn( Collection<Neo4jError> errors ) { if ( errors.isEmpty() ) { return false; } for ( Neo4jError error : errors ) { if ( error.status().code().classification().rollbackTransaction() ) { return true; } } return false; } }
false
community_server_src_main_java_org_neo4j_server_rest_transactional_error_Neo4jError.java
2,765
{ @Override protected NodeRepresentation underlyingObjectToObject( Node node ) { return new NodeRepresentation( node ); } };
false
community_server_src_main_java_org_neo4j_server_rest_web_DatabaseActions.java
2,766
public abstract class TransactionLifecycleException extends Exception { protected TransactionLifecycleException( String message ) { super( message ); } protected TransactionLifecycleException( String message, Throwable cause ) { super( message, cause ); } public Neo4jError toNeo4jError() { return new Neo4jError( getStatusCode(), this ); } protected abstract Status getStatusCode(); }
false
community_server_src_main_java_org_neo4j_server_rest_transactional_error_TransactionLifecycleException.java
2,767
{ @Override public PathRepresentation<WeightedPath> from( WeightedPath path ) { return new WeightedPathRepresentation( path ); } };
false
community_server_src_main_java_org_neo4j_server_rest_web_DatabaseActions.java
2,768
{ @Override public PathRepresentation<Path> from( Path path ) { return new PathRepresentation<>( path ); } };
false
community_server_src_main_java_org_neo4j_server_rest_web_DatabaseActions.java
2,769
{ @Override public Representation apply( ConstraintDefinition from ) { return new ConstraintDefinitionRepresentation( from ); } };
false
community_server_src_main_java_org_neo4j_server_rest_web_DatabaseActions.java
2,770
public class DatabaseActions { public static final String SCORE_ORDER = "score"; public static final String RELEVANCE_ORDER = "relevance"; public static final String INDEX_ORDER = "index"; private final GraphDatabaseAPI graphDb; private final LeaseManager leases; private final ForceMode defaultForceMode; private final TraversalDescriptionBuilder traversalDescriptionBuilder; private final boolean enableScriptSandboxing; private final PropertySettingStrategy propertySetter; public static class Provider extends InjectableProvider<DatabaseActions> { private final DatabaseActions database; public Provider( DatabaseActions database ) { super( DatabaseActions.class ); this.database = database; } @Override public DatabaseActions getValue( HttpContext c ) { return database; } } private final Function<ConstraintDefinition, Representation> CONSTRAINT_DEF_TO_REPRESENTATION = new Function<ConstraintDefinition, Representation>() { @Override public Representation apply( ConstraintDefinition from ) { return new ConstraintDefinitionRepresentation( from ); } }; public DatabaseActions( LeaseManager leaseManager, ForceMode defaultForceMode, boolean enableScriptSandboxing, GraphDatabaseAPI graphDatabaseAPI ) { this.leases = leaseManager; this.defaultForceMode = defaultForceMode; this.graphDb = graphDatabaseAPI; this.enableScriptSandboxing = enableScriptSandboxing; this.traversalDescriptionBuilder = new TraversalDescriptionBuilder( enableScriptSandboxing ); this.propertySetter = new PropertySettingStrategy( graphDb ); } public DatabaseActions( LeaseManager leaseManager, ForceMode defaultForceMode, GraphDatabaseAPI graphDatabaseAPI ) { this( leaseManager, defaultForceMode, true, graphDatabaseAPI ); } public DatabaseActions forceMode( ForceMode forceMode ) { return forceMode == defaultForceMode || forceMode == null ? this : new DatabaseActions( leases, forceMode, enableScriptSandboxing, graphDb ); } private Node node( long id ) throws NodeNotFoundException { try { return graphDb.getNodeById( id ); } catch ( NotFoundException e ) { throw new NodeNotFoundException( String.format( "Cannot find node with id [%d] in database.", id ) ); } } private Relationship relationship( long id ) throws RelationshipNotFoundException { try { return graphDb.getRelationshipById( id ); } catch ( NotFoundException e ) { throw new RelationshipNotFoundException(); } } // API public DatabaseRepresentation root() { return new DatabaseRepresentation(); } // Nodes public NodeRepresentation createNode( Map<String, Object> properties, Label... labels ) throws PropertyValueException { Node node = graphDb.createNode(); propertySetter.setProperties( node, properties ); if ( labels != null ) { for ( Label label : labels ) { node.addLabel( label ); } } return new NodeRepresentation( node ); } public NodeRepresentation getNode( long nodeId ) throws NodeNotFoundException { return new NodeRepresentation( node( nodeId ) ); } public void deleteNode( long nodeId ) throws NodeNotFoundException, OperationFailureException { Node node = node( nodeId ); if ( node.hasRelationship() ) { throw new OperationFailureException( String.format( "The node with id %d cannot be deleted. Check that the node is orphaned before deletion.", nodeId ) ); } node.delete(); } // Property keys public Representation getAllPropertyKeys() { Collection<ValueRepresentation> propKeys = asSet( map( new Function<String, ValueRepresentation>() { @Override public ValueRepresentation apply( String key ) { return ValueRepresentation.string( key ); } }, GlobalGraphOperations.at( graphDb ).getAllPropertyKeys() ) ); return new ListRepresentation( RepresentationType.STRING, propKeys ); } // Node properties public Representation getNodeProperty( long nodeId, String key ) throws NodeNotFoundException, NoSuchPropertyException { Node node = node( nodeId ); try { return PropertiesRepresentation.value( node.getProperty( key ) ); } catch ( NotFoundException e ) { throw new NoSuchPropertyException( node, key ); } } public void setNodeProperty( long nodeId, String key, Object value ) throws PropertyValueException, NodeNotFoundException { Node node = node( nodeId ); propertySetter.setProperty( node, key, value ); } public void removeNodeProperty( long nodeId, String key ) throws NodeNotFoundException, NoSuchPropertyException { Node node = node( nodeId ); if ( node.removeProperty( key ) == null ) { throw new NoSuchPropertyException( node, key ); } } public PropertiesRepresentation getAllNodeProperties( long nodeId ) throws NodeNotFoundException { return new PropertiesRepresentation( node( nodeId ) ); } public void setAllNodeProperties( long nodeId, Map<String, Object> properties ) throws PropertyValueException, NodeNotFoundException { propertySetter.setAllProperties( node( nodeId ), properties ); } public void removeAllNodeProperties( long nodeId ) throws NodeNotFoundException, PropertyValueException { propertySetter.setAllProperties( node( nodeId ), null ); } // Labels public void addLabelToNode( long nodeId, Collection<String> labelNames ) throws NodeNotFoundException, BadInputException { try { Node node = node( nodeId ); for ( String labelName : labelNames ) { node.addLabel( label( labelName ) ); } } catch ( ConstraintViolationException e ) { throw new BadInputException( "Unable to add label, see nested exception.", e ); } } public void setLabelsOnNode( long nodeId, Collection<String> labels ) throws NodeNotFoundException, BadInputException { Node node = node( nodeId ); try { // Remove current labels for ( Label label : node.getLabels() ) { node.removeLabel( label ); } // Add new labels for ( String labelName : labels ) { node.addLabel( label( labelName ) ); } } catch ( ConstraintViolationException e ) { throw new BadInputException( "Unable to add label, see nested exception.", e ); } } public void removeLabelFromNode( long nodeId, String labelName ) throws NodeNotFoundException { node( nodeId ).removeLabel( label( labelName ) ); } public ListRepresentation getNodeLabels( long nodeId ) throws NodeNotFoundException { Iterable<String> labels = new IterableWrapper<String, Label>( node( nodeId ).getLabels() ) { @Override protected String underlyingObjectToObject( Label object ) { return object.name(); } }; return ListRepresentation.string( labels ); } public String[] getNodeIndexNames() { return graphDb.index().nodeIndexNames(); } public String[] getRelationshipIndexNames() { return graphDb.index().relationshipIndexNames(); } public IndexRepresentation createNodeIndex( Map<String, Object> indexSpecification ) { final String indexName = (String) indexSpecification.get( "name" ); assertIsLegalIndexName( indexName ); if ( indexSpecification.containsKey( "config" ) ) { @SuppressWarnings("unchecked") Map<String, String> config = (Map<String, String>) indexSpecification.get( "config" ); graphDb.index().forNodes( indexName, config ); return new NodeIndexRepresentation( indexName, config ); } graphDb.index().forNodes( indexName ); return new NodeIndexRepresentation( indexName, Collections.<String, String>emptyMap() ); } public IndexRepresentation createRelationshipIndex( Map<String, Object> indexSpecification ) { final String indexName = (String) indexSpecification.get( "name" ); assertIsLegalIndexName( indexName ); if ( indexSpecification.containsKey( "config" ) ) { @SuppressWarnings("unchecked") Map<String, String> config = (Map<String, String>) indexSpecification.get( "config" ); graphDb.index().forRelationships( indexName, config ); return new RelationshipIndexRepresentation( indexName, config ); } graphDb.index().forRelationships( indexName ); return new RelationshipIndexRepresentation( indexName, Collections.<String, String>emptyMap() ); } public void removeNodeIndex( String indexName ) { if ( !graphDb.index().existsForNodes( indexName ) ) { throw new NotFoundException( "No node index named '" + indexName + "'." ); } graphDb.index().forNodes( indexName ).delete(); } public void removeRelationshipIndex( String indexName ) { if ( !graphDb.index().existsForRelationships( indexName ) ) { throw new NotFoundException( "No relationship index named '" + indexName + "'." ); } graphDb.index().forRelationships( indexName ).delete(); } public boolean nodeIsIndexed( String indexName, String key, Object value, long nodeId ) { Index<Node> index = graphDb.index().forNodes( indexName ); Node expectedNode = graphDb.getNodeById( nodeId ); IndexHits<Node> hits = index.get( key, value ); return iterableContains( hits, expectedNode ); } public boolean relationshipIsIndexed( String indexName, String key, Object value, long relationshipId ) { Index<Relationship> index = graphDb.index().forRelationships( indexName ); Relationship expectedNode = graphDb.getRelationshipById( relationshipId ); IndexHits<Relationship> hits = index.get( key, value ); return iterableContains( hits, expectedNode ); } private <T> boolean iterableContains( Iterable<T> iterable, T expectedElement ) { for ( T possibleMatch : iterable ) { if ( possibleMatch.equals( expectedElement ) ) { return true; } } return false; } public Representation isAutoIndexerEnabled( String type ) { AutoIndexer<? extends PropertyContainer> index = getAutoIndexerForType( type ); return ValueRepresentation.bool( index.isEnabled() ); } public void setAutoIndexerEnabled( String type, boolean enable ) { AutoIndexer<? extends PropertyContainer> index = getAutoIndexerForType( type ); index.setEnabled( enable ); } private AutoIndexer<? extends PropertyContainer> getAutoIndexerForType( String type ) { final IndexManager indexManager = graphDb.index(); switch ( type ) { case "node": return indexManager.getNodeAutoIndexer(); case "relationship": return indexManager.getRelationshipAutoIndexer(); default: throw new IllegalArgumentException( "invalid type " + type ); } } public Representation getAutoIndexedProperties( String type ) { AutoIndexer<? extends PropertyContainer> indexer = getAutoIndexerForType( type ); return ListRepresentation.string( indexer.getAutoIndexedProperties() ); } public void startAutoIndexingProperty( String type, String property ) { AutoIndexer<? extends PropertyContainer> indexer = getAutoIndexerForType( type ); indexer.startAutoIndexingProperty( property ); } public void stopAutoIndexingProperty( String type, String property ) { AutoIndexer<? extends PropertyContainer> indexer = getAutoIndexerForType( type ); indexer.stopAutoIndexingProperty( property ); } // Relationships public enum RelationshipDirection { all( Direction.BOTH ), in( Direction.INCOMING ), out( Direction.OUTGOING ); final Direction internal; private RelationshipDirection( Direction internal ) { this.internal = internal; } } public RelationshipRepresentation createRelationship( long startNodeId, long endNodeId, String type, Map<String, Object> properties ) throws StartNodeNotFoundException, EndNodeNotFoundException, PropertyValueException { Node start, end; try { start = node( startNodeId ); } catch ( NodeNotFoundException e ) { throw new StartNodeNotFoundException(); } try { end = node( endNodeId ); } catch ( NodeNotFoundException e ) { throw new EndNodeNotFoundException(); } Relationship rel = start.createRelationshipTo( end, DynamicRelationshipType.withName( type ) ); propertySetter.setProperties( rel, properties ); return new RelationshipRepresentation( rel ); } public RelationshipRepresentation getRelationship( long relationshipId ) throws RelationshipNotFoundException { return new RelationshipRepresentation( relationship( relationshipId ) ); } public void deleteRelationship( long relationshipId ) throws RelationshipNotFoundException { relationship( relationshipId ).delete(); } @SuppressWarnings("unchecked") public ListRepresentation getNodeRelationships( long nodeId, RelationshipDirection direction, Collection<String> types ) throws NodeNotFoundException { Node node = node( nodeId ); Expander expander; if ( types.isEmpty() ) { expander = Traversal.expanderForAllTypes( direction.internal ); } else { expander = Traversal.emptyExpander(); for ( String type : types ) { expander = expander.add( DynamicRelationshipType.withName( type ), direction.internal ); } } return RelationshipRepresentation.list( expander.expand( node ) ); } // Relationship properties public PropertiesRepresentation getAllRelationshipProperties( long relationshipId ) throws RelationshipNotFoundException { return new PropertiesRepresentation( relationship( relationshipId ) ); } public Representation getRelationshipProperty( long relationshipId, String key ) throws NoSuchPropertyException, RelationshipNotFoundException { Relationship relationship = relationship( relationshipId ); try { return PropertiesRepresentation.value( relationship.getProperty( key ) ); } catch ( NotFoundException e ) { throw new NoSuchPropertyException( relationship, key ); } } public void setAllRelationshipProperties( long relationshipId, Map<String, Object> properties ) throws PropertyValueException, RelationshipNotFoundException { propertySetter.setAllProperties( relationship( relationshipId ), properties ); } public void setRelationshipProperty( long relationshipId, String key, Object value ) throws PropertyValueException, RelationshipNotFoundException { Relationship relationship = relationship( relationshipId ); propertySetter.setProperty( relationship, key, value ); } public void removeAllRelationshipProperties( long relationshipId ) throws RelationshipNotFoundException, PropertyValueException { propertySetter.setAllProperties( relationship( relationshipId ), null ); } public void removeRelationshipProperty( long relationshipId, String key ) throws RelationshipNotFoundException, NoSuchPropertyException { Relationship relationship = relationship( relationshipId ); if ( relationship.removeProperty( key ) == null ) { throw new NoSuchPropertyException( relationship, key ); } } public Representation nodeIndexRoot() { return new NodeIndexRootRepresentation( graphDb.index() ); } public Representation relationshipIndexRoot() { return new RelationshipIndexRootRepresentation( graphDb.index() ); } public IndexedEntityRepresentation addToRelationshipIndex( String indexName, String key, String value, long relationshipId ) { Relationship relationship = graphDb.getRelationshipById( relationshipId ); Index<Relationship> index = graphDb.index().forRelationships( indexName ); index.add( relationship, key, value ); return new IndexedEntityRepresentation( relationship, key, value, new RelationshipIndexRepresentation( indexName, Collections.<String, String>emptyMap() ) ); } public IndexedEntityRepresentation addToNodeIndex( String indexName, String key, String value, long nodeId ) { Node node = graphDb.getNodeById( nodeId ); Index<Node> index = graphDb.index().forNodes( indexName ); index.add( node, key, value ); return new IndexedEntityRepresentation( node, key, value, new NodeIndexRepresentation( indexName, Collections.<String, String>emptyMap() ) ); } public void removeFromNodeIndex( String indexName, String key, String value, long id ) { graphDb.index().forNodes( indexName ).remove( graphDb.getNodeById( id ), key, value ); } public void removeFromNodeIndexNoValue( String indexName, String key, long id ) { graphDb.index().forNodes( indexName ).remove( graphDb.getNodeById( id ), key ); } public void removeFromNodeIndexNoKeyValue( String indexName, long id ) { graphDb.index().forNodes( indexName ).remove( graphDb.getNodeById( id ) ); } public void removeFromRelationshipIndex( String indexName, String key, String value, long id ) { graphDb.index().forRelationships( indexName ).remove( graphDb.getRelationshipById( id ), key, value ); } public void removeFromRelationshipIndexNoValue( String indexName, String key, long id ) { graphDb.index().forRelationships( indexName ).remove( graphDb.getRelationshipById( id ), key ); } public void removeFromRelationshipIndexNoKeyValue( String indexName, long id ) { graphDb.index().forRelationships( indexName ).remove( graphDb.getRelationshipById( id ) ); } public IndexedEntityRepresentation getIndexedNode( String indexName, String key, String value, long id ) { if ( !nodeIsIndexed( indexName, key, value, id ) ) { throw new NotFoundException(); } Node node = graphDb.getNodeById( id ); return new IndexedEntityRepresentation( node, key, value, new NodeIndexRepresentation( indexName, Collections.<String, String>emptyMap() ) ); } public IndexedEntityRepresentation getIndexedRelationship( String indexName, String key, String value, long id ) { if ( !relationshipIsIndexed( indexName, key, value, id ) ) { throw new NotFoundException(); } Relationship node = graphDb.getRelationshipById( id ); return new IndexedEntityRepresentation( node, key, value, new RelationshipIndexRepresentation( indexName, Collections.<String, String>emptyMap() ) ); } public ListRepresentation getIndexedNodes( String indexName, final String key, final String value ) { if ( !graphDb.index().existsForNodes( indexName ) ) { throw new NotFoundException(); } Index<Node> index = graphDb.index().forNodes( indexName ); final IndexRepresentation indexRepresentation = new NodeIndexRepresentation( indexName ); final IndexHits<Node> indexHits = index.get( key, value ); final IterableWrapper<Representation, Node> results = new IterableWrapper<Representation, Node>( indexHits ) { @Override protected Representation underlyingObjectToObject( Node node ) { return new IndexedEntityRepresentation( node, key, value, indexRepresentation ); } }; return new ListRepresentation( RepresentationType.NODE, results ); } public ListRepresentation getIndexedNodesByQuery( String indexName, String query, String sort ) { return getIndexedNodesByQuery( indexName, null, query, sort ); } public ListRepresentation getIndexedNodesByQuery( String indexName, String key, String query, String sort ) { if ( !graphDb.index().existsForNodes( indexName ) ) { throw new NotFoundException(); } if ( query == null ) { return toListNodeRepresentation(); } Index<Node> index = graphDb.index().forNodes( indexName ); IndexResultOrder order = getOrdering( sort ); QueryContext queryCtx = order.updateQueryContext( new QueryContext( query ) ); IndexHits<Node> result = index.query( key, queryCtx ); return toListNodeRepresentation( result, order ); } private ListRepresentation toListNodeRepresentation() { return new ListRepresentation( RepresentationType.NODE, Collections.<Representation>emptyList() ); } private ListRepresentation toListNodeRepresentation( final IndexHits<Node> result, final IndexResultOrder order ) { if ( result == null ) { return new ListRepresentation( RepresentationType.NODE, Collections.<Representation>emptyList() ); } final IterableWrapper<Representation, Node> results = new IterableWrapper<Representation, Node>( result ) { @Override protected Representation underlyingObjectToObject( Node node ) { final NodeRepresentation nodeRepresentation = new NodeRepresentation( node ); if ( order == null ) { return nodeRepresentation; } return order.getRepresentationFor( nodeRepresentation, result.currentScore() ); } }; return new ListRepresentation( RepresentationType.NODE, results ); } private ListRepresentation toListRelationshipRepresentation() { return new ListRepresentation( RepresentationType.RELATIONSHIP, Collections.<Representation>emptyList() ); } private ListRepresentation toListRelationshipRepresentation( final IndexHits<Relationship> result, final IndexResultOrder order ) { if ( result == null ) { return new ListRepresentation( RepresentationType.RELATIONSHIP, Collections.<Representation>emptyList() ); } final IterableWrapper<Representation, Relationship> results = new IterableWrapper<Representation, Relationship>( result ) { @Override protected Representation underlyingObjectToObject( Relationship rel ) { final RelationshipRepresentation relationshipRepresentation = new RelationshipRepresentation( rel ); if ( order != null ) { return order.getRepresentationFor( relationshipRepresentation, result.currentScore() ); } return relationshipRepresentation; } }; return new ListRepresentation( RepresentationType.RELATIONSHIP, results ); } public Pair<IndexedEntityRepresentation, Boolean> getOrCreateIndexedNode( String indexName, String key, String value, Long nodeOrNull, Map<String, Object> properties ) throws BadInputException, NodeNotFoundException { assertIsLegalIndexName( indexName ); Node result; boolean created; if ( nodeOrNull != null ) { if ( properties != null ) { throw new BadInputException( "Cannot specify properties for a new node, " + "when a node to index is specified." ); } Node node = node( nodeOrNull ); result = graphDb.index().forNodes( indexName ).putIfAbsent( node, key, value ); created = result == null; if ( created ) { UniqueNodeFactory factory = new UniqueNodeFactory( indexName, properties ); UniqueEntity<Node> entity = factory.getOrCreateWithOutcome( key, value ); // when given a node id, return as created if that node was newly added to the index created = entity.entity().getId() == node.getId() || entity.wasCreated(); result = entity.entity(); } } else { if ( properties != null ) { for ( Map.Entry<String, Object> entry : properties.entrySet() ) { entry.setValue( propertySetter.convert( entry.getValue() ) ); } } UniqueNodeFactory factory = new UniqueNodeFactory( indexName, properties ); UniqueEntity<Node> entity = factory.getOrCreateWithOutcome( key, value ); result = entity.entity(); created = entity.wasCreated(); } return Pair.of( new IndexedEntityRepresentation( result, key, value, new NodeIndexRepresentation( indexName, Collections.<String, String>emptyMap() ) ), created ); } public Pair<IndexedEntityRepresentation, Boolean> getOrCreateIndexedRelationship( String indexName, String key, String value, Long relationshipOrNull, Long startNode, String type, Long endNode, Map<String, Object> properties ) throws BadInputException, RelationshipNotFoundException, NodeNotFoundException { assertIsLegalIndexName( indexName ); Relationship result; boolean created; if ( relationshipOrNull != null ) { if ( startNode != null || type != null || endNode != null || properties != null ) { throw new BadInputException( "Either specify a relationship to index uniquely, " + "or the means for creating it." ); } Relationship relationship = relationship( relationshipOrNull ); result = graphDb.index().forRelationships( indexName ).putIfAbsent( relationship, key, value ); if ( created = result == null ) { UniqueRelationshipFactory factory = new UniqueRelationshipFactory( indexName, relationship.getStartNode(), relationship.getEndNode(), relationship.getType().name(), properties ); UniqueEntity<Relationship> entity = factory.getOrCreateWithOutcome( key, value ); // when given a relationship id, return as created if that relationship was newly added to the index created = entity.entity().getId() == relationship.getId() || entity.wasCreated(); result = entity.entity(); } } else if ( startNode == null || type == null || endNode == null ) { throw new BadInputException( "Either specify a relationship to index uniquely, " + "or the means for creating it." ); } else { UniqueRelationshipFactory factory = new UniqueRelationshipFactory( indexName, node( startNode ), node( endNode ), type, properties ); UniqueEntity<Relationship> entity = factory.getOrCreateWithOutcome( key, value ); result = entity.entity(); created = entity.wasCreated(); } return Pair.of( new IndexedEntityRepresentation( result, key, value, new RelationshipIndexRepresentation( indexName, Collections.<String, String>emptyMap() ) ), created ); } 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() ); } } } private class UniqueNodeFactory extends UniqueFactory.UniqueNodeFactory { private final Map<String, Object> properties; UniqueNodeFactory( String index, Map<String, Object> properties ) { super( graphDb, index ); this.properties = properties; } @Override protected void initialize( Node node, Map<String, Object> indexed ) { for ( Map.Entry<String, Object> property : (properties == null ? indexed : properties).entrySet() ) { node.setProperty( property.getKey(), property.getValue() ); } } } public Representation getAutoIndexedNodes( String key, String value ) { ReadableIndex<Node> index = graphDb.index().getNodeAutoIndexer().getAutoIndex(); return toListNodeRepresentation( index.get( key, value ), null ); } public ListRepresentation getAutoIndexedNodesByQuery( String query ) { if ( query != null ) { ReadableIndex<Node> index = graphDb.index().getNodeAutoIndexer().getAutoIndex(); return toListNodeRepresentation( index.query( query ), null ); } return toListNodeRepresentation(); } public ListRepresentation getIndexedRelationships( String indexName, final String key, final String value ) { if ( !graphDb.index().existsForRelationships( indexName ) ) { throw new NotFoundException(); } Index<Relationship> index = graphDb.index().forRelationships( indexName ); final IndexRepresentation indexRepresentation = new RelationshipIndexRepresentation( indexName ); IterableWrapper<Representation, Relationship> result = new IterableWrapper<Representation, Relationship>( index.get( key, value ) ) { @Override protected Representation underlyingObjectToObject( Relationship relationship ) { return new IndexedEntityRepresentation( relationship, key, value, indexRepresentation ); } }; return new ListRepresentation( RepresentationType.RELATIONSHIP, result ); } public ListRepresentation getIndexedRelationshipsByQuery( String indexName, String query, String sort ) { return getIndexedRelationshipsByQuery( indexName, null, query, sort ); } public ListRepresentation getIndexedRelationshipsByQuery( String indexName, String key, String query, String sort ) { if ( !graphDb.index().existsForRelationships( indexName ) ) { throw new NotFoundException(); } if ( query == null ) { return toListRelationshipRepresentation(); } Index<Relationship> index = graphDb.index().forRelationships( indexName ); IndexResultOrder order = getOrdering( sort ); QueryContext queryCtx = order.updateQueryContext( new QueryContext( query ) ); return toListRelationshipRepresentation( index.query( key, queryCtx ), order ); } public Representation getAutoIndexedRelationships( String key, String value ) { ReadableRelationshipIndex index = graphDb.index().getRelationshipAutoIndexer().getAutoIndex(); return toListRelationshipRepresentation( index.get( key, value ), null ); } public ListRepresentation getAutoIndexedRelationshipsByQuery( String query ) { ReadableRelationshipIndex index = graphDb.index().getRelationshipAutoIndexer().getAutoIndex(); final IndexHits<Relationship> results = query != null ? index.query( query ) : null; return toListRelationshipRepresentation( results, null ); } // Traversal public ListRepresentation traverse( long startNode, Map<String, Object> description, final TraverserReturnType returnType ) { Node node = graphDb.getNodeById( startNode ); TraversalDescription traversalDescription = traversalDescriptionBuilder.from( description ); final Iterable<Path> paths = traversalDescription.traverse( node ); return toListPathRepresentation( paths, returnType ); } private ListRepresentation toListPathRepresentation( final Iterable<Path> paths, final TraverserReturnType returnType ) { final IterableWrapper<Representation, Path> result = new IterableWrapper<Representation, Path>( paths ) { @Override protected Representation underlyingObjectToObject( Path position ) { return returnType.toRepresentation( position ); } }; return new ListRepresentation( returnType.repType, result ); } public ListRepresentation pagedTraverse( String traverserId, TraverserReturnType returnType ) { Lease lease = leases.getLeaseById( traverserId ); if ( lease == null ) { throw new NotFoundException( String.format( "The traverser with id [%s] was not found", traverserId ) ); } PagedTraverser traverser = lease.getLeasedItemAndRenewLease(); List<Path> paths = traverser.next(); if ( paths != null ) { return toListPathRepresentation( paths, returnType ); } else { leases.remove( traverserId ); // Yuck. throw new NotFoundException( String.format( "The results for paged traverser with id [%s] have been fully enumerated", traverserId ) ); } } public String createPagedTraverser( long nodeId, Map<String, Object> description, int pageSize, int leaseTime ) { Node node = graphDb.getNodeById( nodeId ); TraversalDescription traversalDescription = traversalDescriptionBuilder.from( description ); PagedTraverser traverser = new PagedTraverser( traversalDescription.traverse( node ), pageSize ); return leases.createLease( leaseTime, traverser ).getId(); } public boolean removePagedTraverse( String traverserId ) { Lease lease = leases.getLeaseById( traverserId ); if ( lease == null ) { return false; } else { leases.remove( lease.getId() ); return true; } } // Graph algos @SuppressWarnings("rawtypes") public PathRepresentation findSinglePath( long startId, long endId, Map<String, Object> map ) { FindParams findParams = new FindParams( startId, endId, map ).invoke(); PathFinder finder = findParams.getFinder(); Node startNode = findParams.getStartNode(); Node endNode = findParams.getEndNode(); Path path = finder.findSinglePath( startNode, endNode ); if ( path == null ) { throw new NotFoundException(); } return findParams.pathRepresentationOf( path ); } @SuppressWarnings({"rawtypes", "unchecked"}) public ListRepresentation findPaths( long startId, long endId, Map<String, Object> map ) { final FindParams findParams = new FindParams( startId, endId, map ).invoke(); PathFinder finder = findParams.getFinder(); Node startNode = findParams.getStartNode(); Node endNode = findParams.getEndNode(); Iterable paths = finder.findAllPaths( startNode, endNode ); IterableWrapper<PathRepresentation, Path> pathRepresentations = new IterableWrapper<PathRepresentation, Path>( paths ) { @Override protected PathRepresentation underlyingObjectToObject( Path path ) { return findParams.pathRepresentationOf( path ); } }; return new ListRepresentation( RepresentationType.PATH, pathRepresentations ); } private class FindParams { private final long startId; private final long endId; private final Map<String, Object> map; private Node startNode; private Node endNode; private PathFinder<? extends Path> finder; @SuppressWarnings("rawtypes") private PathRepresentationCreator representationCreator = PATH_REPRESENTATION_CREATOR; public FindParams( final long startId, final long endId, final Map<String, Object> map ) { this.startId = startId; this.endId = endId; this.map = map; } public Node getStartNode() { return startNode; } public Node getEndNode() { return endNode; } public PathFinder<? extends Path> getFinder() { return finder; } @SuppressWarnings("unchecked") public PathRepresentation<? extends Path> pathRepresentationOf( Path path ) { return representationCreator.from( path ); } public FindParams invoke() { startNode = graphDb.getNodeById( startId ); endNode = graphDb.getNodeById( endId ); Integer maxDepthObj = (Integer) map.get( "max_depth" ); int maxDepth = (maxDepthObj != null) ? maxDepthObj : 1; RelationshipExpander expander = RelationshipExpanderBuilder.describeRelationships( map ); String algorithm = (String) map.get( "algorithm" ); algorithm = (algorithm != null) ? algorithm : "shortestPath"; finder = getAlgorithm( algorithm, expander, maxDepth ); return this; } private PathFinder<? extends Path> getAlgorithm( String algorithm, RelationshipExpander expander, int maxDepth ) { if ( algorithm.equals( "shortestPath" ) ) { return GraphAlgoFactory.shortestPath( expander, maxDepth ); } else if ( algorithm.equals( "allSimplePaths" ) ) { return GraphAlgoFactory.allSimplePaths( expander, maxDepth ); } else if ( algorithm.equals( "allPaths" ) ) { return GraphAlgoFactory.allPaths( expander, maxDepth ); } else if ( algorithm.equals( "dijkstra" ) ) { String costProperty = (String) map.get( "cost_property" ); Number defaultCost = (Number) map.get( "default_cost" ); CostEvaluator<Double> costEvaluator = defaultCost == null ? CommonEvaluators.doubleCostEvaluator( costProperty ) : CommonEvaluators.doubleCostEvaluator( costProperty, defaultCost.doubleValue() ); representationCreator = WEIGHTED_PATH_REPRESENTATION_CREATOR; return GraphAlgoFactory.dijkstra( expander, costEvaluator ); } throw new RuntimeException( "Failed to find matching algorithm" ); } } /* * This enum binds the parameter-string-to-result-order mapping and * the kind of results returned. This is not correct in general but * at the time of writing it is the way things are done and is * quite handy. Feel free to rip out if requirements change. */ private enum IndexResultOrder { INDEX_ORDER { @Override QueryContext updateQueryContext( QueryContext original ) { return original.sort( Sort.INDEXORDER ); } }, RELEVANCE_ORDER { @Override QueryContext updateQueryContext( QueryContext original ) { return original.sort( Sort.RELEVANCE ); } }, SCORE_ORDER { @Override QueryContext updateQueryContext( QueryContext original ) { return original.sortByScore(); } }, NONE { @Override Representation getRepresentationFor( Representation delegate, float score ) { return delegate; } @Override QueryContext updateQueryContext( QueryContext original ) { return original; } }; Representation getRepresentationFor( Representation delegate, float score ) { if ( delegate instanceof NodeRepresentation ) { return new ScoredNodeRepresentation( (NodeRepresentation) delegate, score ); } if ( delegate instanceof RelationshipRepresentation ) { return new ScoredRelationshipRepresentation( (RelationshipRepresentation) delegate, score ); } return delegate; } abstract QueryContext updateQueryContext( QueryContext original ); } private final IndexResultOrder getOrdering( String order ) { if ( INDEX_ORDER.equalsIgnoreCase( order ) ) { return IndexResultOrder.INDEX_ORDER; } else if ( RELEVANCE_ORDER.equalsIgnoreCase( order ) ) { return IndexResultOrder.RELEVANCE_ORDER; } else if ( SCORE_ORDER.equalsIgnoreCase( order ) ) { return IndexResultOrder.SCORE_ORDER; } else { return IndexResultOrder.NONE; } } private interface PathRepresentationCreator<T extends Path> { PathRepresentation<T> from( T path ); } private static final PathRepresentationCreator<Path> PATH_REPRESENTATION_CREATOR = new PathRepresentationCreator<Path>() { @Override public PathRepresentation<Path> from( Path path ) { return new PathRepresentation<>( path ); } }; private static final PathRepresentationCreator<WeightedPath> WEIGHTED_PATH_REPRESENTATION_CREATOR = new PathRepresentationCreator<WeightedPath>() { @Override public PathRepresentation<WeightedPath> from( WeightedPath path ) { return new WeightedPathRepresentation( path ); } }; private void assertIsLegalIndexName( String indexName ) { if ( indexName == null || indexName.equals( "" ) ) { throw new IllegalArgumentException( "Index name must not be empty." ); } } public ListRepresentation getNodesWithLabel( String labelName, Map<String, Object> properties ) { Iterable<Node> nodes; if ( properties.size() == 0 ) { nodes = GlobalGraphOperations.at( graphDb ).getAllNodesWithLabel( label( labelName ) ); } else if ( properties.size() == 1 ) { Map.Entry<String, Object> prop = Iterables.single( properties.entrySet() ); nodes = graphDb.findNodesByLabelAndProperty( label( labelName ), prop.getKey(), prop.getValue() ); } else { throw new IllegalArgumentException( "Too many properties specified. Either specify one property to " + "filter by, or none at all." ); } IterableWrapper<NodeRepresentation, Node> nodeRepresentations = new IterableWrapper<NodeRepresentation, Node>( nodes ) { @Override protected NodeRepresentation underlyingObjectToObject( Node node ) { return new NodeRepresentation( node ); } }; return new ListRepresentation( RepresentationType.NODE, nodeRepresentations ); } public ListRepresentation getAllLabels() { Collection<ValueRepresentation> labelNames = asSet( map( new Function<Label, ValueRepresentation>() { @Override public ValueRepresentation apply( Label label ) { return ValueRepresentation.string( label.name() ); } }, GlobalGraphOperations.at( graphDb ).getAllLabels() ) ); return new ListRepresentation( RepresentationType.STRING, labelNames ); } public IndexDefinitionRepresentation createSchemaIndex( String labelName, Iterable<String> propertyKey ) { IndexCreator indexCreator = graphDb.schema().indexFor( label( labelName ) ); for ( String key : propertyKey ) { indexCreator = indexCreator.on( key ); } return new IndexDefinitionRepresentation( indexCreator.create() ); } public ListRepresentation getSchemaIndexes() { Iterable<IndexDefinition> definitions = graphDb.schema().getIndexes(); Iterable<IndexDefinitionRepresentation> representations = map( new Function<IndexDefinition, IndexDefinitionRepresentation>() { @Override public IndexDefinitionRepresentation apply( IndexDefinition definition ) { return new IndexDefinitionRepresentation( definition ); } }, definitions ); return new ListRepresentation( RepresentationType.INDEX_DEFINITION, representations ); } public ListRepresentation getSchemaIndexes( String labelName ) { Iterable<IndexDefinition> definitions = graphDb.schema().getIndexes( label( labelName ) ); Iterable<IndexDefinitionRepresentation> representations = map( new Function<IndexDefinition, IndexDefinitionRepresentation>() { @Override public IndexDefinitionRepresentation apply( IndexDefinition definition ) { return new IndexDefinitionRepresentation( definition ); } }, definitions ); return new ListRepresentation( RepresentationType.INDEX_DEFINITION, representations ); } public boolean dropSchemaIndex( String labelName, String propertyKey ) { boolean found = false; for ( IndexDefinition index : graphDb.schema().getIndexes( label( labelName ) ) ) { // TODO Assumption about single property key if ( propertyKey.equals( single( index.getPropertyKeys() ) ) ) { index.drop(); found = true; break; } } return found; } public ConstraintDefinitionRepresentation createPropertyUniquenessConstraint( String labelName, Iterable<String> propertyKeys ) { ConstraintCreator constraintCreator = graphDb.schema().constraintFor( label( labelName ) ); for ( String key : propertyKeys ) { constraintCreator = constraintCreator.assertPropertyIsUnique( key ); } ConstraintDefinition constraintDefinition = constraintCreator.create(); return new ConstraintDefinitionRepresentation( constraintDefinition ); } public boolean dropPropertyUniquenessConstraint( String labelName, Iterable<String> propertyKeys ) { final Set<String> propertyKeysSet = asSet( propertyKeys ); ConstraintDefinition constraint = singleOrNull( filteredConstraints( labelName, propertyUniquenessFilter( propertyKeysSet ) ) ); if ( constraint != null ) { constraint.drop(); } return constraint != null; } public ListRepresentation getPropertyUniquenessConstraint( String labelName, Iterable<String> propertyKeys ) { Set<String> propertyKeysSet = asSet( propertyKeys ); Iterable<ConstraintDefinition> constraints = filteredConstraints( labelName, propertyUniquenessFilter( propertyKeysSet ) ); if ( constraints.iterator().hasNext() ) { Iterable<Representation> representationIterable = map( CONSTRAINT_DEF_TO_REPRESENTATION, constraints ); return new ListRepresentation( CONSTRAINT_DEFINITION, representationIterable ); } else { throw new IllegalArgumentException( String.format( "Constraint with label %s for properties %s does not exist", labelName, propertyKeys ) ); } } private Iterable<ConstraintDefinition> filteredConstraints( String labelName, Predicate<ConstraintDefinition> filter ) { Iterable<ConstraintDefinition> constraints = graphDb.schema().getConstraints( label( labelName ) ); return filter( filter, constraints ); } private Iterable<ConstraintDefinition> filteredConstraints( String labelName, final ConstraintType type ) { return filter(new Predicate<ConstraintDefinition>(){ @Override public boolean accept( ConstraintDefinition item ) { return item.isConstraintType( type ); } }, graphDb.schema().getConstraints( label( labelName ) ) ); } private Predicate<ConstraintDefinition> propertyUniquenessFilter( final Set<String> propertyKeysSet ) { return new Predicate<ConstraintDefinition>() { @Override public boolean accept( ConstraintDefinition item ) { return item.isConstraintType( ConstraintType.UNIQUENESS ) && propertyKeysSet.equals( asSet( item.getPropertyKeys() ) ); } }; } public ListRepresentation getConstraints() { return new ListRepresentation( CONSTRAINT_DEFINITION, map( CONSTRAINT_DEF_TO_REPRESENTATION, graphDb.schema().getConstraints() ) ); } public ListRepresentation getLabelConstraints( String labelName ) { return new ListRepresentation( CONSTRAINT_DEFINITION, map( CONSTRAINT_DEF_TO_REPRESENTATION, filteredConstraints( labelName, Predicates.<ConstraintDefinition>TRUE() ) ) ); } public Representation getLabelUniquenessConstraints( String labelName ) { return new ListRepresentation( CONSTRAINT_DEFINITION, map( CONSTRAINT_DEF_TO_REPRESENTATION, filteredConstraints( labelName, ConstraintType.UNIQUENESS ) ) ); } }
false
community_server_src_main_java_org_neo4j_server_rest_web_DatabaseActions.java
2,771
@Path("/cypher") public class CypherService { private static final String PARAMS_KEY = "params"; private static final String QUERY_KEY = "query"; private static final String INCLUDE_STATS_PARAM = "includeStats"; private static final String INCLUDE_PLAN_PARAM = "includePlan"; private static final String PROFILE_PARAM = "profile"; private CypherExecutor cypherExecutor; private OutputFormat output; private InputFormat input; public CypherService( @Context CypherExecutor cypherExecutor, @Context InputFormat input, @Context OutputFormat output ) { this.cypherExecutor = cypherExecutor; this.input = input; this.output = output; } public OutputFormat getOutputFormat() { return output; } @POST @SuppressWarnings({ "unchecked" }) public Response cypher(String body, @QueryParam( INCLUDE_STATS_PARAM ) boolean includeStats, @QueryParam( INCLUDE_PLAN_PARAM ) boolean includePlan, @QueryParam( PROFILE_PARAM ) boolean profile) throws BadInputException { Map<String,Object> command = input.readMap( body ); if( !command.containsKey(QUERY_KEY) ) { return output.badRequest(new BadInputException( "You have to provide the 'query' parameter." )); } String query = (String) command.get( QUERY_KEY ); Map<String, Object> params = null; try { params = (Map<String, Object>) (command.containsKey( PARAMS_KEY ) && command.get( PARAMS_KEY ) != null ? command.get( PARAMS_KEY ) : new HashMap<String, Object>()); } catch ( ClassCastException e ) { return output.badRequest( new IllegalArgumentException("Parameters must be a JSON map") ); } try { if ( profile ) { ExecutionResult result = cypherExecutor.getExecutionEngine().profile( query, params ); return output.ok(new CypherResultRepresentation( result, /* includeStats=*/includeStats, true )); } else { ExecutionResult result = cypherExecutor.getExecutionEngine().execute( query, params ); return output.ok(new CypherResultRepresentation( result, /* includeStats=*/includeStats, includePlan )); } } catch ( Throwable e ) { if (e.getCause() instanceof CypherException) { return output.badRequest( e.getCause() ); } else { return output.badRequest( e ); } } } }
false
community_server_src_main_java_org_neo4j_server_rest_web_CypherService.java
2,772
public class CollectUserAgentFilterTest { private final CollectUserAgentFilter filter = new CollectUserAgentFilter(); @Rule public Mute mute = muteAll(); @Test public void shouldRecordASingleUserAgent() { filter.filter( request( "the-agent" ) ); assertThat( filter.getUserAgents(), hasItem( "the-agent" ) ); } @Test public void shouldOnlyRecordTheFirstFieldOfTheUserAgentString() { filter.filter( request( "the-agent other-info" ) ); assertThat( filter.getUserAgents(), hasItem( "the-agent" ) ); } @Test public void shouldRecordMultipleUserAgents() { filter.filter( request( "agent1" ) ); filter.filter( request( "agent2" ) ); assertThat( filter.getUserAgents(), hasItems( "agent1", "agent2" ) ); } @Test public void shouldNotReportDuplicates() { filter.filter( request( "the-agent" ) ); filter.filter( request( "the-agent" ) ); assertThat( filter.getUserAgents(), hasSize( 1 ) ); } @Test public void shouldClearRecordedValues() { filter.filter( request( "the-agent" ) ); filter.reset(); assertThat( filter.getUserAgents(), hasSize( 0 ) ); } @Test public void shouldCopeIfThereIsNoUserAgentHeader() { filter.filter( request() ); assertThat( filter.getUserAgents(), hasSize( 0 ) ); } @Test public void shouldCopeIfThereIsMoreThanOneUserAgentHeader() { filter.filter( request( "agent1", "agent2" ) ); assertThat( filter.getUserAgents(), hasSize( 1 ) ); } @Test public void shouldSwallowAnyExceptionsThrownByTheRequest() { ContainerRequest request = mock( ContainerRequest.class ); stub(request.getRequestHeader( anyString() )).toThrow( new RuntimeException() ); filter.filter( request ); } @Test public void shouldReturnTheRequest() { ContainerRequest original = request( "the-agent" ); ContainerRequest returned = filter.filter( original ); assertSame( original, returned ); } private static ContainerRequest request( String... userAgent ) { ContainerRequest request = mock( ContainerRequest.class ); List<String> headers = Arrays.asList( userAgent ); stub(request.getRequestHeader( "User-Agent" )).toReturn( headers ); return request; } }
false
community_server_src_test_java_org_neo4j_server_rest_web_CollectUserAgentFilterTest.java
2,773
public class CollectUserAgentFilterIT extends AbstractRestFunctionalTestBase { private static FunctionalTestHelper functionalTestHelper; @BeforeClass public static void setupServer() throws IOException { functionalTestHelper = new FunctionalTestHelper( server() ); } @Test public void shouldRecordUserAgent() throws Exception { sendRequest( "test/1.0" ); assertThat(CollectUserAgentFilter.instance().getUserAgents(), hasItem( "test/1.0" )); } private void sendRequest(String userAgent) { String url = functionalTestHelper.baseUri().toString(); JaxRsResponse resp = RestRequest.req().header( "User-Agent", userAgent ).get(url); String json = resp.getEntity(); resp.close(); assertEquals(json, 200, resp.getStatus()); } }
false
community_server_src_test_java_org_neo4j_server_rest_web_CollectUserAgentFilterIT.java
2,774
public class CollectUserAgentFilter implements ContainerRequestFilter { private static CollectUserAgentFilter INSTANCE; public static CollectUserAgentFilter instance() { if ( INSTANCE == null ) { new CollectUserAgentFilter(); } return INSTANCE; } private final Collection<String> userAgents = Collections.synchronizedCollection( new HashSet<String>() ); public CollectUserAgentFilter() { // Bear with me here. There are some fairly unpleasant constraints that have led me to this solution. // // 1. The UDC can't depend on server components, because it has to work in embedded. So the read side of this // in DefaultUdcInformationCollector is invoked by reflection. For that reason we need the actual list of // user agents in a running system to be statically accessible. // // 2. On the write side, Jersey's contract is that we provide a class which it instantiates itself. So we need // to write the list of user agents from any instance. However Jersey will only create one instance, so we // can rely on the constructor being called only once in the running system. // // 3. For testing purposes, we would like to be able to create independent instances; otherwise we get problems // with global state being carried over between tests. INSTANCE = this; } @Override public ContainerRequest filter( ContainerRequest request ) { try { List<String> headers = request.getRequestHeader( "User-Agent" ); if ( ! headers.isEmpty() ) { userAgents.add( headers.get( 0 ).split( " " )[0] ); } } catch ( RuntimeException e ) { // We're fine with that } return request; } public void reset() { userAgents.clear(); } public Collection<String> getUserAgents() { return Collections.unmodifiableCollection( userAgents ); } }
false
community_server_src_main_java_org_neo4j_server_rest_web_CollectUserAgentFilter.java
2,775
{ @Override public void write( int i ) throws IOException { output.write( i ); } };
false
community_server_src_main_java_org_neo4j_server_rest_web_BatchOperationService.java
2,776
{ @Override public void write( final OutputStream output ) throws IOException, WebApplicationException { try { final ServletOutputStream servletOutputStream = new ServletOutputStream() { @Override public void write( int i ) throws IOException { output.write( i ); } }; new StreamingBatchOperations( webServer ).readAndExecuteOperations( uriInfo, httpHeaders, body, servletOutputStream ); representationWriteHandler.onRepresentationWritten(); } catch ( Exception e ) { LOGGER.warn( "Error executing batch request ", e ); } finally { representationWriteHandler.onRepresentationFinal(); } } };
false
community_server_src_main_java_org_neo4j_server_rest_web_BatchOperationService.java
2,777
@Path("/batch") public class BatchOperationService { private static final Logger LOGGER = Log.getLogger(BatchOperationService.class); private final OutputFormat output; private final WebServer webServer; private RepresentationWriteHandler representationWriteHandler = RepresentationWriteHandler.DO_NOTHING; public BatchOperationService( @Context WebServer webServer, @Context OutputFormat output ) { this.output = output; this.webServer = webServer; } public void setRepresentationWriteHandler( RepresentationWriteHandler representationWriteHandler ) { this.representationWriteHandler = representationWriteHandler; } @POST public Response performBatchOperations(@Context UriInfo uriInfo, @Context HttpHeaders httpHeaders, InputStream body) { if ( isStreaming( httpHeaders ) ) { return batchProcessAndStream( uriInfo, httpHeaders, body ); } return batchProcess( uriInfo, httpHeaders, body ); } private Response batchProcessAndStream( final UriInfo uriInfo, final HttpHeaders httpHeaders, final InputStream body ) { try { final StreamingOutput stream = new StreamingOutput() { @Override public void write( final OutputStream output ) throws IOException, WebApplicationException { try { final ServletOutputStream servletOutputStream = new ServletOutputStream() { @Override public void write( int i ) throws IOException { output.write( i ); } }; new StreamingBatchOperations( webServer ).readAndExecuteOperations( uriInfo, httpHeaders, body, servletOutputStream ); representationWriteHandler.onRepresentationWritten(); } catch ( Exception e ) { LOGGER.warn( "Error executing batch request ", e ); } finally { representationWriteHandler.onRepresentationFinal(); } } }; return Response.ok(stream) .type( HttpHeaderUtils.mediaTypeWithCharsetUtf8(MediaType.APPLICATION_JSON_TYPE) ).build(); } catch ( Exception e ) { return output.serverError( e ); } } private Response batchProcess( UriInfo uriInfo, HttpHeaders httpHeaders, InputStream body ) { try { NonStreamingBatchOperations batchOperations = new NonStreamingBatchOperations( webServer ); BatchOperationResults results = batchOperations.performBatchJobs( uriInfo, httpHeaders, body ); Response res = Response.ok().entity(results.toJSON()) .type(HttpHeaderUtils.mediaTypeWithCharsetUtf8(MediaType.APPLICATION_JSON_TYPE)).build(); representationWriteHandler.onRepresentationWritten(); return res; } catch ( Exception e ) { return output.serverError( e ); } finally { representationWriteHandler.onRepresentationFinal(); } } private boolean isStreaming( HttpHeaders httpHeaders ) { if ( "true".equalsIgnoreCase( httpHeaders.getRequestHeaders().getFirst( StreamingFormat.STREAM_HEADER ) ) ) { return true; } for ( MediaType mediaType : httpHeaders.getAcceptableMediaTypes() ) { Map<String, String> parameters = mediaType.getParameters(); if ( parameters.containsKey( "stream" ) && "true".equalsIgnoreCase( parameters.get( "stream" ) ) ) { return true; } } return false; } }
false
community_server_src_main_java_org_neo4j_server_rest_web_BatchOperationService.java
2,778
public class AllowAjaxFilter implements ContainerResponseFilter { private static final String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin"; private static final String ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods"; private static final String ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers"; private static final String ACCESS_CONTROL_REQUEST_METHOD = "access-control-request-method"; private static final String ACCESS_CONTROL_REQUEST_HEADERS = "access-control-request-headers"; public ContainerResponse filter( ContainerRequest request, ContainerResponse response ) { response.getHttpHeaders() .add( ACCESS_CONTROL_ALLOW_ORIGIN, "*" ); // Allow all forms of requests if ( request.getRequestHeaders() .containsKey( ACCESS_CONTROL_REQUEST_METHOD ) ) { for ( String value : request.getRequestHeaders() .get( ACCESS_CONTROL_REQUEST_METHOD ) ) { response.getHttpHeaders() .add( ACCESS_CONTROL_ALLOW_METHODS, value ); } } // Allow all types of headers if ( request.getRequestHeaders() .containsKey( ACCESS_CONTROL_REQUEST_HEADERS ) ) { for ( String value : request.getRequestHeaders() .get( ACCESS_CONTROL_REQUEST_HEADERS ) ) { response.getHttpHeaders() .add( ACCESS_CONTROL_ALLOW_HEADERS, value ); } } return response; } }
false
community_server_src_main_java_org_neo4j_server_rest_web_AllowAjaxFilter.java
2,779
{ @Override protected boolean matchesSafely( HTTP.Response response ) { Map<String, Object> content = response.content(); @SuppressWarnings("unchecked") List<Map<String, Object>> errors = ((List<Map<String, Object>>) content.get( "errors" )); for ( Map<String, Object> error : errors ) { if( error.containsKey( "stackTrace" ) ) { return false; } } return true; } @Override public void describeTo( Description description ) { description.appendText( "contains stack traces" ); } };
false
community_server_src_test_java_org_neo4j_server_rest_transactional_integration_TransactionMatchers.java
2,780
{ @Override protected boolean matchesSafely( HTTP.Response response ) { try { Iterator<JsonNode> errors = response.get( "errors" ).iterator(); Iterator<Status> expected = iterator( expectedErrors ); while ( expected.hasNext() ) { assertTrue( errors.hasNext() ); assertThat( errors.next().get( "code" ).asText(), equalTo( expected.next().code().serialize() ) ); } if ( errors.hasNext() ) { JsonNode error = errors.next(); fail( "Expected no more errors, but got " + error.get( "code" ) + " - '" + error.get( "message" ) + "'." ); } return true; } catch ( JsonParseException e ) { return false; } } @Override public void describeTo( Description description ) { } };
false
community_server_src_test_java_org_neo4j_server_rest_transactional_integration_TransactionMatchers.java
2,781
{ @Override protected boolean matchesSafely( String item ) { return regex.matcher( item ).matches(); } @Override public void describeTo( Description description ) { description.appendText( "matching regex: " ).appendValue( pattern ); } };
false
community_server_src_test_java_org_neo4j_server_rest_transactional_integration_TransactionMatchers.java
2,782
{ @Override protected boolean matchesSafely( String item ) { try { return RFC1123.parseTimestamp( item ).getTime() > 0; } catch ( ParseException e ) { return false; } } @Override public void describeTo( Description description ) { description.appendText( "valid RFC1134 timestamp" ); } };
false
community_server_src_test_java_org_neo4j_server_rest_transactional_integration_TransactionMatchers.java
2,783
public class TransactionMatchers { static Matcher<String> isValidRFCTimestamp() { return new TypeSafeMatcher<String>() { @Override protected boolean matchesSafely( String item ) { try { return RFC1123.parseTimestamp( item ).getTime() > 0; } catch ( ParseException e ) { return false; } } @Override public void describeTo( Description description ) { description.appendText( "valid RFC1134 timestamp" ); } }; } static Matcher<String> matches( final String pattern ) { final Pattern regex = Pattern.compile( pattern ); return new TypeSafeMatcher<String>() { @Override protected boolean matchesSafely( String item ) { return regex.matcher( item ).matches(); } @Override public void describeTo( Description description ) { description.appendText( "matching regex: " ).appendValue( pattern ); } }; } public static Matcher<? super HTTP.Response> containsNoErrors() { return hasErrors(); } public static Matcher<? super HTTP.Response> hasErrors( final Status... expectedErrors ) { return new TypeSafeMatcher<HTTP.Response>() { @Override protected boolean matchesSafely( HTTP.Response response ) { try { Iterator<JsonNode> errors = response.get( "errors" ).iterator(); Iterator<Status> expected = iterator( expectedErrors ); while ( expected.hasNext() ) { assertTrue( errors.hasNext() ); assertThat( errors.next().get( "code" ).asText(), equalTo( expected.next().code().serialize() ) ); } if ( errors.hasNext() ) { JsonNode error = errors.next(); fail( "Expected no more errors, but got " + error.get( "code" ) + " - '" + error.get( "message" ) + "'." ); } return true; } catch ( JsonParseException e ) { return false; } } @Override public void describeTo( Description description ) { } }; } @SuppressWarnings("WhileLoopReplaceableByForEach") public static long countNodes(GraphDatabaseService graphdb) { try ( Transaction ignore = graphdb.beginTx() ) { long count = 0; Iterator<Node> allNodes = GlobalGraphOperations.at( graphdb ).getAllNodes().iterator(); while ( allNodes.hasNext() ) { allNodes.next(); count++; } return count; } } public static Matcher<? super HTTP.Response> containsNoStackTraces() { return new TypeSafeMatcher<HTTP.Response>() { @Override protected boolean matchesSafely( HTTP.Response response ) { Map<String, Object> content = response.content(); @SuppressWarnings("unchecked") List<Map<String, Object>> errors = ((List<Map<String, Object>>) content.get( "errors" )); for ( Map<String, Object> error : errors ) { if( error.containsKey( "stackTrace" ) ) { return false; } } return true; } @Override public void describeTo( Description description ) { description.appendText( "contains stack traces" ); } }; } }
false
community_server_src_test_java_org_neo4j_server_rest_transactional_integration_TransactionMatchers.java
2,784
public class TransactionIT extends AbstractRestFunctionalTestBase { private final HTTP.Builder http = HTTP.withBaseUri( "http://localhost:7474" ); @Test public void begin__execute__commit() throws Exception { long nodesInDatabaseBeforeTransaction = countNodes(); // begin Response begin = http.POST( "/db/data/transaction" ); assertThat( begin.status(), equalTo( 201 ) ); assertThat( begin.location(), matches( "http://localhost:\\d+/db/data/transaction/\\d+" ) ); String commitResource = begin.stringFromContent( "commit" ); assertThat( commitResource, matches( "http://localhost:\\d+/db/data/transaction/\\d" + "+/commit" ) ); assertThat( begin.get("transaction").get("expires").asText(), isValidRFCTimestamp()); // execute Response execute = http.POST( begin.location(), quotedJson( "{ 'statements': [ { 'statement': 'CREATE n' } ] }" ) ); assertThat( execute.status(), equalTo( 200 ) ); assertThat( execute.get("transaction").get("expires").asText(), isValidRFCTimestamp()); // commit Response commit = http.POST( commitResource ); assertThat( commit.status(), equalTo( 200 ) ); assertThat( countNodes(), equalTo( nodesInDatabaseBeforeTransaction + 1 ) ); } @Test public void begin__execute__rollback() throws Exception { long nodesInDatabaseBeforeTransaction = countNodes(); // begin Response begin = http.POST( "/db/data/transaction" ); assertThat( begin.status(), equalTo( 201 ) ); assertThat( begin.location(), matches( "http://localhost:\\d+/db/data/transaction/\\d+" ) ); // execute http.POST( begin.location(), quotedJson( "{ 'statements': [ { 'statement': 'CREATE n' } ] }" ) ); // rollback Response commit = http.DELETE( begin.location() ); assertThat( commit.status(), equalTo( 200 ) ); assertThat( countNodes(), equalTo( nodesInDatabaseBeforeTransaction ) ); } @Test public void begin__execute_and_commit() throws Exception { long nodesInDatabaseBeforeTransaction = countNodes(); // begin Response begin = http.POST( "/db/data/transaction" ); assertThat( begin.status(), equalTo( 201 ) ); assertThat( begin.location(), containsString( "/db/data/transaction" ) ); String commitResource = begin.stringFromContent( "commit" ); assertThat( commitResource, equalTo( begin.location() + "/commit" ) ); // execute and commit Response commit = http.POST( commitResource, quotedJson( "{ 'statements': [ { 'statement': 'CREATE n' } ] }" ) ); assertThat( commit, containsNoErrors()); assertThat( commit.status(), equalTo( 200 ) ); assertThat( countNodes(), equalTo( nodesInDatabaseBeforeTransaction + 1 ) ); } @Test public void begin_and_execute__commit() throws Exception { long nodesInDatabaseBeforeTransaction = countNodes(); // begin and execute Response begin = http.POST( "/db/data/transaction", quotedJson( "{ 'statements': [ { 'statement': 'CREATE n' " + "} ] }" ) ); String commitResource = begin.stringFromContent( "commit" ); // commit Response commit = http.POST( commitResource ); assertThat( commit.status(), equalTo( 200 ) ); assertThat( countNodes(), equalTo( nodesInDatabaseBeforeTransaction + 1 ) ); } @Test public void begin__execute__commit__execute() throws Exception { // begin Response begin = http.POST( "/db/data/transaction" ); String commitResource = begin.stringFromContent( "commit" ); // execute http.POST( begin.location(), quotedJson( "{ 'statements': [ { 'statement': 'CREATE n' } ] }" ) ); // commit http.POST( commitResource ); // execute Response execute = http.POST( begin.location(), quotedJson( "{ 'statements': [ { 'statement': 'CREATE n' } ] }" ) ); assertThat( execute.status(), equalTo( 404 ) ); assertThat(execute, hasErrors( Status.Transaction.UnknownId )); } @Test public void begin_and_execute_and_commit() throws Exception { long nodesInDatabaseBeforeTransaction = countNodes(); // begin and execute and commit Response begin = http.POST( "/db/data/transaction/commit", quotedJson( "{ 'statements': [ { 'statement': 'CREATE n' } ] }" ) ); assertThat( begin.status(), equalTo( 200 ) ); assertThat( countNodes(), equalTo( nodesInDatabaseBeforeTransaction + 1 ) ); } @Test public void begin__execute_multiple__commit() throws Exception { long nodesInDatabaseBeforeTransaction = countNodes(); // begin Response begin = http.POST( "/db/data/transaction" ); String commitResource = begin.stringFromContent( "commit" ); // execute http.POST( begin.location(), quotedJson( "{ 'statements': [ { 'statement': 'CREATE n' }, { 'statement': 'CREATE n' } ] }" ) ); // commit assertThat( http.POST( commitResource ), containsNoErrors() ); assertThat( countNodes(), equalTo( nodesInDatabaseBeforeTransaction + 2 ) ); } @Test public void begin__execute__execute__commit() throws Exception { long nodesInDatabaseBeforeTransaction = countNodes(); // begin Response begin = http.POST( "/db/data/transaction" ); String commitResource = begin.stringFromContent( "commit" ); // execute http.POST( begin.location(), quotedJson( "{ 'statements': [ { 'statement': 'CREATE n' } ] }" ) ); // execute http.POST( begin.location(), quotedJson( "{ 'statements': [ { 'statement': 'CREATE n' } ] }" ) ); // commit http.POST( commitResource ); assertThat( countNodes(), equalTo( nodesInDatabaseBeforeTransaction + 2 ) ); } @Test public void begin_create_two_nodes_delete_one() throws Exception { /* * This issue was reported from the community. It resulted in a refactoring of the interaction * between TxManager and TransactionContexts. */ // GIVEN long nodesInDatabaseBeforeTransaction = countNodes(); Response response = http.POST( "/db/data/transaction/commit", rawPayload( "{ \"statements\" : [{\"statement\" : \"CREATE (n0:DecibelEntity :AlbumGroup{DecibelID : '34a2201b-f4a9-420f-87ae-00a9c691cc5c', Title : 'Dance With Me', ArtistString : 'Ra Ra Riot', MainArtistAlias : 'Ra Ra Riot', OriginalReleaseDate : '2013-01-08', IsCanon : 'False'}) return id(n0)\"}, {\"statement\" : \"CREATE (n1:DecibelEntity :AlbumRelease{DecibelID : '9ed529fa-7c19-11e2-be78-bcaec5bea3c3', Title : 'Dance With Me', ArtistString : 'Ra Ra Riot', MainArtistAlias : 'Ra Ra Riot', LabelName : 'Barsuk Records', FormatNames : 'File', TrackCount : '3', MediaCount : '1', Duration : '460.000000', ReleaseDate : '2013-01-08', ReleaseYear : '2013', ReleaseRegion : 'USA', Cline : 'Barsuk Records', Pline : 'Barsuk Records', CYear : '2013', PYear : '2013', ParentalAdvisory : 'False', IsLimitedEdition : 'False'}) return id(n1)\"}]}" ) ); assertEquals( 200, response.status() ); JsonNode everything = jsonNode( response.rawContent() ); JsonNode result = everything.get( "results" ).get( 0 ); long id = result.get( "data" ).get( 0 ).get( "row" ).get( 0 ).getLongValue(); // WHEN http.POST( "/db/data/cypher", rawPayload( "{\"query\":\"start n = node(" + id + ") delete n\"}" ) ); // THEN assertThat( countNodes(), equalTo( nodesInDatabaseBeforeTransaction+1 ) ); } @Test public void should_include_graph_format_when_requested() throws Exception { // given http.POST( "/db/data/transaction/commit", singleStatement( "CREATE (n:Foo:Bar)" ) ); // when Response response = http.POST( "/db/data/transaction/commit", quotedJson( "{ 'statements': [ { 'statement': 'MATCH (n:Foo) RETURN n', 'resultDataContents':['row','graph'] } ] }" ) ); // then assertThat( response.status(), equalTo( 200 ) ); JsonNode data = response.get( "results" ).get( 0 ).get( "data" ); assertTrue( "data is a list", data.isArray() ); assertEquals( "one entry", 1, data.size() ); JsonNode entry = data.get( 0 ); assertTrue( "entry has row", entry.has( "row" ) ); assertTrue( "entry has graph", entry.has( "graph" ) ); JsonNode nodes = entry.get( "graph" ).get( "nodes" ), rels = entry.get( "graph" ).get( "relationships" ); assertTrue( "nodes is a list", nodes.isArray() ); assertTrue( "relationships is a list", rels.isArray() ); assertEquals( "one node", 1, nodes.size() ); assertEquals( "no relationships", 0, rels.size() ); Set<String> labels = new HashSet<>(); for ( JsonNode node : nodes.get( 0 ).get( "labels" ) ) { labels.add( node.getTextValue() ); } assertEquals( "labels", asSet( "Foo", "Bar" ), labels ); } @Test public void should_serialize_collect_correctly() throws Exception { // given http.POST( "/db/data/transaction/commit", singleStatement( "CREATE (n:Foo)" ) ); // when Response response = http.POST( "/db/data/transaction/commit", quotedJson( "{ 'statements': [ { 'statement': 'MATCH (n:Foo) RETURN COLLECT(n)' } ] }" ) ); // then assertThat( response.status(), equalTo( 200 ) ); JsonNode data = response.get( "results" ).get(0); assertThat( data.get( "columns" ).get( 0 ).asText(), equalTo( "COLLECT(n)" ) ); assertThat( data.get( "data" ).get(0).get( "row" ).size(), equalTo(1)); assertThat( data.get( "data" ).get( 0 ).get( "row" ).get( 0 ).get( 0 ).size(), equalTo( 0 ) ); assertThat( response.get( "errors" ).size(), equalTo( 0 ) ); } @Test public void shouldSerializeMapsCorrectlyInRowsFormat() throws Exception { Response response = http.POST( "/db/data/transaction/commit", quotedJson( "{ 'statements': [ { 'statement': 'RETURN {one:{two:[true, {three: 42}]}}' } ] }" ) ); // then assertThat( response.status(), equalTo( 200 ) ); JsonNode data = response.get( "results" ).get(0); JsonNode row = data.get( "data" ).get( 0 ).get( "row" ); assertThat( row.size(), equalTo(1)); JsonNode firstCell = row.get( 0 ); assertThat( firstCell.get( "one" ).get( "two" ).size(), is( 2 )); assertThat( firstCell.get( "one" ).get( "two" ).get( 0 ).asBoolean(), is( true ) ); assertThat( firstCell.get( "one" ).get( "two" ).get( 1 ).get( "three" ).asInt(), is( 42 )); assertThat( response.get( "errors" ).size(), equalTo(0)); } @Test public void shouldSerializeMapsCorrectlyInRestFormat() throws Exception { Response response = http.POST( "/db/data/transaction/commit", quotedJson( "{ 'statements': [ { 'statement': " + "'RETURN {one:{two:[true, {three: 42}]}}', 'resultDataContents':['rest'] } ] }" ) ); // then assertThat( response.status(), equalTo( 200 ) ); JsonNode data = response.get( "results" ).get( 0 ); JsonNode rest = data.get( "data" ).get( 0 ).get( "rest" ); assertThat( rest.size(), equalTo( 1 ) ); JsonNode firstCell = rest.get( 0 ); assertThat( firstCell.get( "one" ).get( "two" ).size(), is( 2 ) ); assertThat( firstCell.get( "one" ).get( "two" ).get( 0 ).asBoolean(), is( true ) ); assertThat( firstCell.get( "one" ).get( "two" ).get( 1 ).get( "three" ).asInt(), is( 42 ) ); assertThat( response.get( "errors" ).size(), equalTo( 0 ) ); } private HTTP.RawPayload singleStatement( String statement ) { return rawPayload( "{\"statements\":[{\"statement\":\"" + statement + "\"}]}" ); } private long countNodes() { try ( Transaction transaction = graphdb().beginTx() ) { long count = 0; for ( Iterator<Node> allNodes = GlobalGraphOperations.at( graphdb() ).getAllNodes().iterator(); allNodes.hasNext(); allNodes.next() ) { count++; } transaction.failure(); return count; } } }
false
community_server_src_test_java_org_neo4j_server_rest_transactional_integration_TransactionIT.java
2,785
public class TransactionErrorIT extends AbstractRestFunctionalTestBase { @Test public void begin__commit_with_invalid_cypher() throws Exception { long nodesInDatabaseBeforeTransaction = countNodes(); // begin HTTP.Response response = POST( txUri(), quotedJson( "{ 'statements': [ { 'statement': 'CREATE n' } ] }" ) ); String commitResource = response.stringFromContent( "commit" ); // commit with invalid cypher response = POST( commitResource, quotedJson( "{ 'statements': [ { 'statement': 'CREATE ;;' } ] }" ) ); assertThat( response.status(), is( 200 ) ); assertThat( response, hasErrors( InvalidSyntax ) ); assertThat( response, containsNoStackTraces()); assertThat( countNodes(), equalTo( nodesInDatabaseBeforeTransaction ) ); } @Test public void begin__commit_with_malformed_json() throws Exception { long nodesInDatabaseBeforeTransaction = countNodes(); // begin HTTP.Response begin = POST( txUri(), quotedJson( "{ 'statements': [ { 'statement': 'CREATE n' } ] }" ) ); String commitResource = begin.stringFromContent( "commit" ); // commit with malformed json HTTP.Response response = POST( commitResource, rawPayload( "[{asd,::}]" ) ); assertThat( response.status(), is( 200 ) ); assertThat( response, hasErrors( InvalidFormat ) ); assertThat( countNodes(), equalTo( nodesInDatabaseBeforeTransaction ) ); } private String txUri() { return getDataUri() + "transaction"; } private long countNodes() { return TransactionMatchers.countNodes( graphdb() ); } }
false
community_server_src_test_java_org_neo4j_server_rest_transactional_integration_TransactionErrorIT.java
2,786
public class CompactJsonFormatTest { private OutputFormat json; @Before public void createOutputFormat() throws Exception { json = new OutputFormat( new CompactJsonFormat(), 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 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 ); } }
false
community_server_src_test_java_org_neo4j_server_rest_repr_formats_CompactJsonFormatTest.java
2,787
EXCEPTION( Representation.EXCEPTION ) { @Override String render( Map<String, Object> data ) { return JsonHelper.createJsonFrom( data ); } };
false
community_server_src_main_java_org_neo4j_server_rest_repr_formats_CompactJsonFormat.java
2,788
STRING( Representation.STRING ) { @Override String render( Map<String, Object> serialized ) { return JsonHelper.createJsonFrom( serialized ); } },
false
community_server_src_main_java_org_neo4j_server_rest_repr_formats_CompactJsonFormat.java
2,789
public class LeaseTest { private static final long SIXTY_SECONDS = 60; @Test public void shouldReturnHexIdentifierString() throws Exception { Lease lease = new Lease( mock( PagedTraverser.class ), SIXTY_SECONDS, new FakeClock() ); assertThat( lease.getId(), containsOnlyHex() ); } @Test( expected = LeaseAlreadyExpiredException.class ) public void shouldNotAllowLeasesInThePast() throws Exception { FakeClock clock = new FakeClock(); new Lease( mock( PagedTraverser.class ), oneMinuteInThePast(), clock ); } private long oneMinuteInThePast() { return SIXTY_SECONDS * -1; } @Test public void leasesShouldExpire() throws Exception { FakeClock clock = new FakeClock(); Lease lease = new Lease( mock( PagedTraverser.class ), SIXTY_SECONDS, clock ); clock.forward( 10, TimeUnit.MINUTES ); assertTrue( lease.expired() ); } @Test public void shouldRenewLeaseForSamePeriod() { FakeClock clock = new FakeClock(); Lease lease = new Lease( mock( PagedTraverser.class ), SIXTY_SECONDS, clock ); clock.forward( 30, TimeUnit.SECONDS ); lease.getLeasedItemAndRenewLease(); // has side effect of renewing the // lease clock.forward( 30, TimeUnit.SECONDS ); assertFalse( lease.expired() ); clock.forward( 10, TimeUnit.MINUTES ); assertTrue( lease.expired() ); } }
false
community_server_src_test_java_org_neo4j_server_rest_paging_LeaseTest.java
2,790
@Provider public class LeaseManagerProvider extends InjectableProvider<LeaseManager> { private final LeaseManager leaseManager; public LeaseManagerProvider(LeaseManager leaseManager) { super( LeaseManager.class ); this.leaseManager = leaseManager; } @Override public LeaseManager getValue( HttpContext arg0 ) { return leaseManager; } }
false
community_server_src_main_java_org_neo4j_server_rest_paging_LeaseManagerProvider.java
2,791
public class LeaseManager { private final Clock clock; private Map<String, Lease> leases = new ConcurrentHashMap<String, Lease>(); public LeaseManager( Clock clock ) { this.clock = clock; } public Lease createLease( long seconds, PagedTraverser leasedTraverser ) throws LeaseAlreadyExpiredException { if ( seconds < 1 ) { return null; } Lease lease = new Lease( leasedTraverser, seconds, clock ); leases.put( lease.getId(), lease ); return lease; } public Lease getLeaseById( String id ) { pruneOldLeasesByNaivelyIteratingThroughAllOfThem(); Lease lease = leases.get( id ); if ( lease != null ) { lease.renew(); } return lease; } private void pruneOldLeasesByNaivelyIteratingThroughAllOfThem() { for ( String key : leases.keySet() ) { try { Lease lease = leases.get( key ); if ( lease.getStartTime() + lease.getPeriod() < clock.currentTimeMillis() ) { remove( key ); } } catch ( Exception e ) { // do nothing - if something goes wrong, it just means another // thread already nuked the lease } } } public Clock getClock() { return clock; } public void remove( String key ) { if ( leases.containsKey( key ) ) { leases.remove( key ); } } }
false
community_server_src_main_java_org_neo4j_server_rest_paging_LeaseManager.java
2,792
public class LeaseAlreadyExpiredException extends RuntimeException { public LeaseAlreadyExpiredException( String message ) { super( message ); } private static final long serialVersionUID = -4827067345302605272L; }
false
community_server_src_main_java_org_neo4j_server_rest_paging_LeaseAlreadyExpiredException.java
2,793
public class Lease { private long startTime; public final PagedTraverser leasedTraverser; private final String id; private long leasePeriod; private final Clock clock; Lease( PagedTraverser leasedTraverser, long leasePeriodInSeconds, Clock clock ) throws LeaseAlreadyExpiredException { if ( leasePeriodInSeconds < 0 ) { throw new LeaseAlreadyExpiredException( String.format( "Negative lease periods [%d] are not permitted", leasePeriodInSeconds ) ); } this.clock = clock; this.leasedTraverser = leasedTraverser; this.startTime = clock.currentTimeMillis(); this.leasePeriod = leasePeriodInSeconds * 1000; this.id = toHexOnly( UUID.randomUUID() ); } public String getId() { return id; } private String toHexOnly( UUID uuid ) { return uuid.toString() .replaceAll( "-", "" ); } public PagedTraverser getLeasedItemAndRenewLease() { renew(); return leasedTraverser; } public void renew() { if ( !expired() ) { startTime = clock.currentTimeMillis(); } } public boolean expired() { return startTime + leasePeriod < clock.currentTimeMillis(); } public long getStartTime() { return startTime; } public long getPeriod() { return leasePeriod; } }
false
community_server_src_main_java_org_neo4j_server_rest_paging_Lease.java
2,794
public class HexMatcher extends TypeSafeMatcher<String> { private static final Pattern pattern = Pattern.compile( "[a-fA-F0-9]*" ); private String candidate; private HexMatcher() { } @Override public void describeTo( Description description ) { description.appendText( String.format( "[%s] is not a pure hexadecimal string", candidate ) ); } @Override public boolean matchesSafely( String candidate ) { this.candidate = candidate; return pattern.matcher( candidate ) .matches(); } @Factory public static Matcher<String> containsOnlyHex() { return new HexMatcher(); } }
false
community_server_src_test_java_org_neo4j_server_rest_paging_HexMatcher.java
2,795
public class UriToDatabaseMatcherTest { @Test public void shouldMatchDefaults() throws Exception { UriToDatabaseMatcher matcher = new UriToDatabaseMatcher(); matcher.add( new GraphDatabaseName( "restbucks" ) ); matcher.add( new GraphDatabaseName( "order" ) ); matcher.add( new GraphDatabaseName( "amazon" ) ); assertEquals( new GraphDatabaseName( "restbucks" ), matcher.lookup( new URI( "http://localhost/restbucks/order/1234" ) ) ); assertEquals( new GraphDatabaseName( "amazon" ), matcher.lookup( new URI( "http://www.amazon.com/amazon/product/0596805829" ) ) ); assertEquals( new GraphDatabaseName( "order" ), matcher.lookup( new URI( "http://restbucks.com/order/1234" ) ) ); } }
false
community_server_src_test_java_org_neo4j_server_rest_domain_UriToDatabaseMatcherTest.java
2,796
private static class Tuple { public GraphDatabaseName graphDatabaseName; public Pattern pattern; public Tuple( Pattern pattern, GraphDatabaseName graphDatabaseName ) { this.pattern = pattern; this.graphDatabaseName = graphDatabaseName; } @Override public String toString() { return pattern.toString() + " => " + graphDatabaseName + System.getProperty( "line.separator" ); } }
false
community_server_src_main_java_org_neo4j_server_rest_domain_UriToDatabaseMatcher.java
2,797
public class UriToDatabaseMatcher { private static ArrayList<Tuple> tuples = new ArrayList<Tuple>(); public GraphDatabaseName lookup( URI requestUri ) { for ( int i = 0; i < tuples.size(); i++ ) { Tuple t = tuples.get( i ); // Matchers aren't thread-safe, so they have to be created // per-request Matcher matcher = t.pattern.matcher( requestUri.getPath() ); if ( matcher.matches() ) { return t.graphDatabaseName; } } return GraphDatabaseName.NO_NAME; } /** * Adds a mapping the given database using the default URI * (/{database_name}) * * @param databaseName */ public void add( GraphDatabaseName databaseName ) { // Patterns are thread safe and immutable, so compile them once only tuples.add( new Tuple( Pattern.compile( "^.*" + databaseName.getName() + ".*$" ), databaseName ) ); } @Override public String toString() { StringBuilder sb = new StringBuilder(); for ( int i = tuples.size() - 1; i >= 0; i-- ) { Tuple t = tuples.get( i ); sb.append( t ); } return sb.toString(); } private static class Tuple { public GraphDatabaseName graphDatabaseName; public Pattern pattern; public Tuple( Pattern pattern, GraphDatabaseName graphDatabaseName ) { this.pattern = pattern; this.graphDatabaseName = graphDatabaseName; } @Override public String toString() { return pattern.toString() + " => " + graphDatabaseName + System.getProperty( "line.separator" ); } } }
false
community_server_src_main_java_org_neo4j_server_rest_domain_UriToDatabaseMatcher.java
2,798
public class URIHelper { public static String encode( String value ) { try { return URLEncoder.encode( value, "utf-8" ) .replaceAll( "\\+", "%20" ); } catch ( UnsupportedEncodingException e ) { throw new RuntimeException( e ); } } }
false
community_server_src_main_java_org_neo4j_server_rest_domain_URIHelper.java
2,799
fullpath( RepresentationType.FULL_PATH ) { @Override public MappingRepresentation toRepresentation( Path position ) { return new FullPathRepresentation( position ); } };
false
community_server_src_main_java_org_neo4j_server_rest_domain_TraverserReturnType.java