Unnamed: 0
int64 0
6.7k
| func
stringlengths 12
89.6k
| target
bool 2
classes | project
stringlengths 45
151
|
|---|---|---|---|
2,300
|
{
@Override
public void joinedCluster( InstanceId member, URI memberUri )
{
port.set( memberUri.getPort() );
latch.countDown();
clients[0].removeClusterListener( this );
}
};
| false
|
enterprise_server-enterprise_src_test_java_org_neo4j_server_enterprise_StandaloneClusterClientIT.java
|
2,301
|
{
@Override
public void enteredCluster( ClusterConfiguration configuration )
{
latch.countDown();
client.removeClusterListener( this );
}
} );
| false
|
enterprise_server-enterprise_src_test_java_org_neo4j_server_enterprise_StandaloneClusterClientIT.java
|
2,302
|
{
@Override
public void run()
{
life.shutdown();
}
} );
| false
|
enterprise_server-enterprise_src_main_java_org_neo4j_server_enterprise_StandaloneClusterClient.java
|
2,303
|
public class ServerTestUtils
{
public static void writePropertyToFile( String name, String value, File propertyFile )
{
Properties properties = loadProperties( propertyFile );
properties.setProperty( name, value );
storeProperties( propertyFile, properties );
}
private static void storeProperties( File propertyFile,
Properties properties )
{
OutputStream out = null;
try
{
out = new FileOutputStream( propertyFile );
properties.store( out, "" );
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
finally
{
safeClose( out );
}
}
private static Properties loadProperties( File propertyFile )
{
Properties properties = new Properties();
if ( propertyFile.exists() )
{
InputStream in = null;
try
{
in = new FileInputStream( propertyFile );
properties.load( in );
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
finally
{
safeClose( in );
}
}
return properties;
}
private static void safeClose( Closeable closeable )
{
if ( closeable != null )
{
try
{
closeable.close();
}
catch ( IOException e )
{
e.printStackTrace();
}
}
}
public static File createTempPropertyFile( File parentDir ) throws IOException
{
return new File( parentDir, "test-" + new Random().nextInt() + ".properties" );
}
}
| false
|
enterprise_server-enterprise_src_test_java_org_neo4j_server_enterprise_ServerTestUtils.java
|
2,304
|
{
@Override
public boolean run()
{
return true;
}
};
| false
|
community_server_src_test_java_org_neo4j_server_helpers_CommunityServerBuilder.java
|
2,305
|
public final class FunctionalTestHelper
{
private final NeoServer server;
private final GraphDbHelper helper;
public static final Client CLIENT = Client.create();
private RestRequest request;
public FunctionalTestHelper( NeoServer server )
{
if ( server.getDatabase() == null )
{
throw new RuntimeException( "Server must be started before using " + getClass().getName() );
}
this.helper = new GraphDbHelper( server.getDatabase() );
this.server = server;
this.request = new RestRequest(server.baseUri().resolve("db/data/"));
}
public static Matcher<String[]> arrayContains( final String element )
{
return new TypeSafeMatcher<String[]>()
{
private String[] array;
@Override
public void describeTo( Description descr )
{
descr.appendText( "The array " )
.appendText( Arrays.toString( array ) )
.appendText( " does not contain <" )
.appendText( element )
.appendText( ">" );
}
@Override
public boolean matchesSafely( String[] array )
{
this.array = array;
for ( String string : array )
{
if ( element == null )
{
if ( string == null ) return true;
}
else if ( element.equals( string ) )
{
return true;
}
}
return false;
}
};
}
public GraphDbHelper getGraphDbHelper()
{
return helper;
}
public String dataUri()
{
return server.baseUri().toString() + "db/data/";
}
public String nodeUri()
{
return dataUri() + "node";
}
public String nodeUri( long id )
{
return nodeUri() + "/" + id;
}
public String nodePropertiesUri( long id )
{
return nodeUri( id ) + "/properties";
}
public String nodePropertyUri( long id, String key )
{
return nodePropertiesUri( id ) + "/" + key;
}
String relationshipUri()
{
return dataUri() + "relationship";
}
public String relationshipUri( long id )
{
return relationshipUri() + "/" + id;
}
public String relationshipPropertiesUri( long id )
{
return relationshipUri( id ) + "/properties";
}
String relationshipPropertyUri( long id, String key )
{
return relationshipPropertiesUri( id ) + "/" + key;
}
public String relationshipsUri( long nodeId, String dir, String... types )
{
StringBuilder typesString = new StringBuilder();
for ( String type : types )
{
typesString.append( typesString.length() > 0 ? "&" : "" );
typesString.append( type );
}
return nodeUri( nodeId ) + "/relationships/" + dir + "/" + typesString;
}
public String indexUri()
{
return dataUri() + "index/";
}
String nodeAutoIndexUri()
{
return indexUri() + "auto/node/";
}
String relationshipAutoIndexUri()
{
return indexUri() + "auto/relationship/";
}
public String nodeIndexUri()
{
return indexUri() + "node/";
}
public String relationshipIndexUri()
{
return indexUri() + "relationship/";
}
public String managementUri()
{
return server.baseUri()
.toString() + "db/manage";
}
public String indexNodeUri( String indexName )
{
return nodeIndexUri() + indexName;
}
public String indexNodeUri( String indexName, String key, Object value )
{
return indexNodeUri( indexName ) + "/" + key + "/" + value;
}
public String indexRelationshipUri( String indexName )
{
return relationshipIndexUri() + indexName;
}
public String indexRelationshipUri( String indexName, String key, Object value )
{
return indexRelationshipUri( indexName ) + "/" + key + "/" + value;
}
public String extensionUri()
{
return dataUri() + "ext";
}
String extensionUri( String name )
{
return extensionUri() + "/" + name;
}
String graphdbExtensionUri( String name, String method )
{
return extensionUri( name ) + "/graphdb/" + method;
}
String nodeExtensionUri( String name, String method, long id )
{
return extensionUri( name ) + "/node/" + id + "/" + method;
}
String relationshipExtensionUri( String name, String method, long id )
{
return extensionUri( name ) + "/relationship/" + id + "/" + method;
}
public GraphDatabaseAPI getDatabase()
{
return server.getDatabase().getGraph();
}
public String webAdminUri()
{
// the trailing slash prevents a 302 redirect
return server.baseUri()
.toString() + "webadmin" + "/";
}
public JaxRsResponse get(String path) {
return request.get(path);
}
public JaxRsResponse get(String path, String data) {
return request.get(path, data);
}
public JaxRsResponse delete(String path) {
return request.delete(path);
}
public JaxRsResponse post(String path, String data) {
return request.post(path, data);
}
public void put(String path, String data) {
request.put(path, data);
}
public long getNodeIdFromUri( String nodeUri )
{
return Long.valueOf( nodeUri.substring( nodeUri.lastIndexOf( "/" ) +1 , nodeUri.length() ) );
}
public long getRelationshipIdFromUri( String relationshipUri )
{
return getNodeIdFromUri( relationshipUri );
}
public Map<String, Object> removeAnyAutoIndex( Map<String, Object> map )
{
Map<String, Object> result = new HashMap<String, Object>();
for ( Map.Entry<String, Object> entry : map.entrySet() )
{
Map<?, ?> innerMap = (Map<?,?>) entry.getValue();
String template = innerMap.get( "template" ).toString();
if ( !template.contains( PATH_AUTO_INDEX.replace("{type}", RestfulGraphDatabase.NODE_AUTO_INDEX_TYPE) ) &&
!template.contains( PATH_AUTO_INDEX.replace("{type}", RestfulGraphDatabase.RELATIONSHIP_AUTO_INDEX_TYPE) ) &&
!template.contains( "_auto_" ) )
result.put( entry.getKey(), entry.getValue() );
}
return result;
}
public URI baseUri()
{
return server.baseUri();
}
}
| false
|
community_server_src_test_java_org_neo4j_server_helpers_FunctionalTestHelper.java
|
2,306
|
{
@Override
public double[] getClonedArray()
{
return property.clone();
}
@Override
public int length()
{
return property.length;
}
@Override
@SuppressWarnings( "boxing" )
protected Double item( int offset )
{
return property[offset];
}
@Override
public Class<?> getType()
{
return property.getClass();
}
}, param );
| false
|
community_server-api_src_main_java_org_neo4j_server_helpers_PropertyTypeDispatcher.java
|
2,307
|
{
private String[] array;
@Override
public void describeTo( Description descr )
{
descr.appendText( "The array " )
.appendText( Arrays.toString( array ) )
.appendText( " does not contain <" )
.appendText( element )
.appendText( ">" );
}
@Override
public boolean matchesSafely( String[] array )
{
this.array = array;
for ( String string : array )
{
if ( element == null )
{
if ( string == null ) return true;
}
else if ( element.equals( string ) )
{
return true;
}
}
return false;
}
};
| false
|
community_server_src_test_java_org_neo4j_server_helpers_FunctionalTestHelper.java
|
2,308
|
{
@Override
public float[] getClonedArray()
{
return property.clone();
}
@Override
public int length()
{
return property.length;
}
@Override
@SuppressWarnings( "boxing" )
protected Float item( int offset )
{
return property[offset];
}
@Override
public Class<?> getType()
{
return property.getClass();
}
}, param );
| false
|
community_server-api_src_main_java_org_neo4j_server_helpers_PropertyTypeDispatcher.java
|
2,309
|
{
@Override
public long[] getClonedArray()
{
return property.clone();
}
@Override
public int length()
{
return property.length;
}
@Override
@SuppressWarnings( "boxing" )
protected Long item( int offset )
{
return property[offset];
}
@Override
public Class<?> getType()
{
return property.getClass();
}
}, param );
| false
|
community_server-api_src_main_java_org_neo4j_server_helpers_PropertyTypeDispatcher.java
|
2,310
|
{
@Override
public int[] getClonedArray()
{
return property.clone();
}
@Override
public int length()
{
return property.length;
}
@Override
@SuppressWarnings( "boxing" )
protected Integer item( int offset )
{
return property[offset];
}
@Override
public Class<?> getType()
{
return property.getClass();
}
}, param );
| false
|
community_server-api_src_main_java_org_neo4j_server_helpers_PropertyTypeDispatcher.java
|
2,311
|
{
@Override
public short[] getClonedArray()
{
return property.clone();
}
@Override
public int length()
{
return property.length;
}
@Override
@SuppressWarnings( "boxing" )
protected Short item( int offset )
{
return property[offset];
}
@Override
public Class<?> getType()
{
return property.getClass();
}
}, param );
| false
|
community_server-api_src_main_java_org_neo4j_server_helpers_PropertyTypeDispatcher.java
|
2,312
|
{
@Override
public char[] getClonedArray()
{
return property.clone();
}
@Override
public int length()
{
return property.length;
}
@Override
@SuppressWarnings( "boxing" )
protected Character item( int offset )
{
return property[offset];
}
@Override
public Class<?> getType()
{
return property.getClass();
}
}, param );
| false
|
community_server-api_src_main_java_org_neo4j_server_helpers_PropertyTypeDispatcher.java
|
2,313
|
{
@Override
public String[] getClonedArray()
{
return property.clone();
}
}, param );
| false
|
community_server-api_src_main_java_org_neo4j_server_helpers_PropertyTypeDispatcher.java
|
2,314
|
{
@Override
@SuppressWarnings( "boxing" )
public boolean[] getClonedArray()
{
boolean[] result = new boolean[property.length];
for ( int i = 0; i < result.length; i++ )
result[i] = property[i];
return result;
}
}, param );
| false
|
community_server-api_src_main_java_org_neo4j_server_helpers_PropertyTypeDispatcher.java
|
2,315
|
{
@Override
@SuppressWarnings( "boxing" )
public double[] getClonedArray()
{
double[] result = new double[property.length];
for ( int i = 0; i < result.length; i++ )
result[i] = property[i];
return result;
}
}, param );
| false
|
community_server-api_src_main_java_org_neo4j_server_helpers_PropertyTypeDispatcher.java
|
2,316
|
{
@Override
@SuppressWarnings( "boxing" )
public float[] getClonedArray()
{
float[] result = new float[property.length];
for ( int i = 0; i < result.length; i++ )
result[i] = property[i];
return result;
}
}, param );
| false
|
community_server-api_src_main_java_org_neo4j_server_helpers_PropertyTypeDispatcher.java
|
2,317
|
{
@Override
@SuppressWarnings( "boxing" )
public long[] getClonedArray()
{
long[] result = new long[property.length];
for ( int i = 0; i < result.length; i++ )
result[i] = property[i];
return result;
}
}, param );
| false
|
community_server-api_src_main_java_org_neo4j_server_helpers_PropertyTypeDispatcher.java
|
2,318
|
{
@Override
@SuppressWarnings( "boxing" )
public int[] getClonedArray()
{
int[] result = new int[property.length];
for ( int i = 0; i < result.length; i++ )
result[i] = property[i];
return result;
}
}, param );
| false
|
community_server-api_src_main_java_org_neo4j_server_helpers_PropertyTypeDispatcher.java
|
2,319
|
{
@Override
@SuppressWarnings( "boxing" )
public short[] getClonedArray()
{
short[] result = new short[property.length];
for ( int i = 0; i < result.length; i++ )
result[i] = property[i];
return result;
}
}, param );
| false
|
community_server-api_src_main_java_org_neo4j_server_helpers_PropertyTypeDispatcher.java
|
2,320
|
{
@Override
@SuppressWarnings( "boxing" )
public char[] getClonedArray()
{
char[] result = new char[property.length];
for ( int i = 0; i < result.length; i++ )
result[i] = property[i];
return result;
}
}, param );
| false
|
community_server-api_src_main_java_org_neo4j_server_helpers_PropertyTypeDispatcher.java
|
2,321
|
{
@Override
public byte[] getClonedArray()
{
return property.clone();
}
@Override
public int length()
{
return property.length;
}
@Override
@SuppressWarnings( "boxing" )
protected Byte item( int offset )
{
return property[offset];
}
@Override
public Class<?> getType()
{
return property.getClass();
}
}, param );
| false
|
community_server-api_src_main_java_org_neo4j_server_helpers_PropertyTypeDispatcher.java
|
2,322
|
public abstract class PropertyTypeDispatcher<K, T>
{
public static abstract class PropertyArray<A, T> implements Iterable<T>
{
private PropertyArray()
{
}
public abstract int length();
public abstract A getClonedArray();
public abstract Class<?> getType();
}
public static void consumeProperties( PropertyTypeDispatcher<String, Void> dispatcher,
PropertyContainer entity )
{
final Iterable<String> keys = entity.getPropertyKeys();
if (keys instanceof List)
{
final List<String> keysList = (List<String>) keys;
for (int i = keysList.size() - 1; i >= 0; i--)
{
dispatchProperty(dispatcher, entity, keysList.get(i));
}
} else
{
for (String key : keys)
{
dispatchProperty(dispatcher, entity, key);
}
}
}
private static void dispatchProperty(PropertyTypeDispatcher<String, Void> dispatcher, PropertyContainer entity, String key) {
Object property = entity.getProperty(key, null);
if ( property == null ) return;
dispatcher.dispatch( property, key );
}
public static <T> Collection<T> dispatchProperties(
PropertyTypeDispatcher<String, T> dispatcher, PropertyContainer entity )
{
List<T> result = new ArrayList<T>();
for ( String key : entity.getPropertyKeys() )
{
Object property = entity.getProperty( key, null );
if ( property == null ) continue;
result.add( dispatcher.dispatch( property, key ) );
}
return result;
}
@SuppressWarnings( "boxing" )
public final T dispatch( Object property, K param )
{
if( property == null)
{
return dispatchNullProperty( param );
} else if ( property instanceof String )
{
return dispatchStringProperty( (String) property, param );
}
else if ( property instanceof Number )
{
return dispatchNumberProperty( (Number) property, param );
}
else if ( property instanceof Boolean )
{
return dispatchBooleanProperty( (Boolean) property, param );
}
else if ( property instanceof Character )
{
return dispatchCharacterProperty( (Character) property, param );
}
else if ( property instanceof String[] )
{
return dispatchStringArrayProperty( (String[]) property, param );
}
else if ( property instanceof Object[] )
{
return dispatchOtherArray( (Object[]) property, param );
}
else
{
Class<?> propertyType = property.getClass();
if ( propertyType.isArray() && propertyType.getComponentType().isPrimitive() )
{
return dispatchPrimitiveArray( property, param );
}
else
{
return dispatchOtherProperty( property, param );
}
}
}
private T dispatchPrimitiveArray( Object property, K param )
{
if ( property instanceof byte[] )
{
return dispatchByteArrayProperty( (byte[]) property, param );
}
else if ( property instanceof char[] )
{
return dispatchCharacterArrayProperty( (char[]) property, param );
}
else if ( property instanceof boolean[] )
{
return dispatchBooleanArrayProperty( (boolean[]) property, param );
}
else if ( property instanceof long[] )
{
return dispatchLongArrayProperty( (long[]) property, param );
}
else if ( property instanceof double[] )
{
return dispatchDoubleArrayProperty( (double[]) property, param );
}
else if ( property instanceof int[] )
{
return dispatchIntegerArrayProperty( (int[]) property, param );
}
else if ( property instanceof short[] )
{
return dispatchShortArrayProperty( (short[]) property, param );
}
else if ( property instanceof float[] )
{
return dispatchFloatArrayProperty( (float[]) property, param );
}
else
{
throw new Error( "Unsupported primitive array type: " + property.getClass() );
}
}
protected T dispatchOtherArray( Object[] property, K param )
{
if ( property instanceof Byte[] )
{
return dispatchByteArrayProperty( (Byte[]) property, param );
}
else if ( property instanceof Character[] )
{
return dispatchCharacterArrayProperty( (Character[]) property, param );
}
else if ( property instanceof Boolean[] )
{
return dispatchBooleanArrayProperty( (Boolean[]) property, param );
}
else if ( property instanceof Long[] )
{
return dispatchLongArrayProperty( (Long[]) property, param );
}
else if ( property instanceof Double[] )
{
return dispatchDoubleArrayProperty( (Double[]) property, param );
}
else if ( property instanceof Integer[] )
{
return dispatchIntegerArrayProperty( (Integer[]) property, param );
}
else if ( property instanceof Short[] )
{
return dispatchShortArrayProperty( (Short[]) property, param );
}
else if ( property instanceof Float[] )
{
return dispatchFloatArrayProperty( (Float[]) property, param );
}
else
{
throw new IllegalArgumentException( "Unsupported property array type: "
+ property.getClass() );
}
}
@SuppressWarnings( "boxing" )
protected T dispatchNumberProperty( Number property, K param )
{
if ( property instanceof Long )
{
return dispatchLongProperty( (Long) property, param );
}
else if ( property instanceof Integer )
{
return dispatchIntegerProperty( (Integer) property, param );
}
else if ( property instanceof Double )
{
return dispatchDoubleProperty( (Double) property, param );
}
else if ( property instanceof Float )
{
return dispatchFloatProperty( (Float) property, param );
}
else if ( property instanceof Short )
{
return dispatchShortProperty( (Short) property, param );
}
else if ( property instanceof Byte )
{
return dispatchByteProperty( (Byte) property, param );
}
else
{
throw new IllegalArgumentException( "Unsupported property type: " + property.getClass() );
}
}
protected T dispatchNullProperty( K param ) {
return null;
}
@SuppressWarnings( "boxing" )
protected abstract T dispatchByteProperty( byte property, K param );
@SuppressWarnings( "boxing" )
protected abstract T dispatchCharacterProperty( char property, K param );
@SuppressWarnings( "boxing" )
protected abstract T dispatchShortProperty( short property, K param );
@SuppressWarnings( "boxing" )
protected abstract T dispatchIntegerProperty( int property, K param );
@SuppressWarnings( "boxing" )
protected abstract T dispatchLongProperty( long property, K param );
@SuppressWarnings( "boxing" )
protected abstract T dispatchFloatProperty( float property, K param );
@SuppressWarnings( "boxing" )
protected abstract T dispatchDoubleProperty( double property, K param );
@SuppressWarnings( "boxing" )
protected abstract T dispatchBooleanProperty( boolean property, K param );
protected T dispatchOtherProperty( Object property, K param) {
throw new IllegalArgumentException( "Unsupported property type: "
+ property.getClass() );
}
protected T dispatchByteArrayProperty( final byte[] property, K param )
{
return dispatchByteArrayProperty( new PrimitiveArray<byte[], Byte>()
{
@Override
public byte[] getClonedArray()
{
return property.clone();
}
@Override
public int length()
{
return property.length;
}
@Override
@SuppressWarnings( "boxing" )
protected Byte item( int offset )
{
return property[offset];
}
@Override
public Class<?> getType()
{
return property.getClass();
}
}, param );
}
protected T dispatchCharacterArrayProperty( final char[] property, K param )
{
return dispatchCharacterArrayProperty( new PrimitiveArray<char[], Character>()
{
@Override
public char[] getClonedArray()
{
return property.clone();
}
@Override
public int length()
{
return property.length;
}
@Override
@SuppressWarnings( "boxing" )
protected Character item( int offset )
{
return property[offset];
}
@Override
public Class<?> getType()
{
return property.getClass();
}
}, param );
}
protected T dispatchShortArrayProperty( final short[] property, K param )
{
return dispatchShortArrayProperty( new PrimitiveArray<short[], Short>()
{
@Override
public short[] getClonedArray()
{
return property.clone();
}
@Override
public int length()
{
return property.length;
}
@Override
@SuppressWarnings( "boxing" )
protected Short item( int offset )
{
return property[offset];
}
@Override
public Class<?> getType()
{
return property.getClass();
}
}, param );
}
protected T dispatchIntegerArrayProperty( final int[] property, K param )
{
return dispatchIntegerArrayProperty( new PrimitiveArray<int[], Integer>()
{
@Override
public int[] getClonedArray()
{
return property.clone();
}
@Override
public int length()
{
return property.length;
}
@Override
@SuppressWarnings( "boxing" )
protected Integer item( int offset )
{
return property[offset];
}
@Override
public Class<?> getType()
{
return property.getClass();
}
}, param );
}
protected T dispatchLongArrayProperty( final long[] property, K param )
{
return dispatchLongArrayProperty( new PrimitiveArray<long[], Long>()
{
@Override
public long[] getClonedArray()
{
return property.clone();
}
@Override
public int length()
{
return property.length;
}
@Override
@SuppressWarnings( "boxing" )
protected Long item( int offset )
{
return property[offset];
}
@Override
public Class<?> getType()
{
return property.getClass();
}
}, param );
}
protected T dispatchFloatArrayProperty( final float[] property, K param )
{
return dispatchFloatArrayProperty( new PrimitiveArray<float[], Float>()
{
@Override
public float[] getClonedArray()
{
return property.clone();
}
@Override
public int length()
{
return property.length;
}
@Override
@SuppressWarnings( "boxing" )
protected Float item( int offset )
{
return property[offset];
}
@Override
public Class<?> getType()
{
return property.getClass();
}
}, param );
}
protected T dispatchDoubleArrayProperty( final double[] property, K param )
{
return dispatchDoubleArrayProperty( new PrimitiveArray<double[], Double>()
{
@Override
public double[] getClonedArray()
{
return property.clone();
}
@Override
public int length()
{
return property.length;
}
@Override
@SuppressWarnings( "boxing" )
protected Double item( int offset )
{
return property[offset];
}
@Override
public Class<?> getType()
{
return property.getClass();
}
}, param );
}
protected T dispatchBooleanArrayProperty( final boolean[] property, K param )
{
return dispatchBooleanArrayProperty( new PrimitiveArray<boolean[], Boolean>()
{
@Override
public boolean[] getClonedArray()
{
return property.clone();
}
@Override
public int length()
{
return property.length;
}
@Override
@SuppressWarnings( "boxing" )
protected Boolean item( int offset )
{
return property[offset];
}
@Override
public Class<?> getType()
{
return property.getClass();
}
}, param );
}
protected T dispatchByteArrayProperty( final Byte[] property, K param )
{
return dispatchByteArrayProperty( new BoxedArray<byte[], Byte>( property )
{
@Override
@SuppressWarnings( "boxing" )
public byte[] getClonedArray()
{
byte[] result = new byte[property.length];
for ( int i = 0; i < result.length; i++ )
result[i] = property[i];
return result;
}
}, param );
}
protected T dispatchCharacterArrayProperty( final Character[] property, K param )
{
return dispatchCharacterArrayProperty( new BoxedArray<char[], Character>( property )
{
@Override
@SuppressWarnings( "boxing" )
public char[] getClonedArray()
{
char[] result = new char[property.length];
for ( int i = 0; i < result.length; i++ )
result[i] = property[i];
return result;
}
}, param );
}
protected T dispatchShortArrayProperty( final Short[] property, K param )
{
return dispatchShortArrayProperty( new BoxedArray<short[], Short>( property )
{
@Override
@SuppressWarnings( "boxing" )
public short[] getClonedArray()
{
short[] result = new short[property.length];
for ( int i = 0; i < result.length; i++ )
result[i] = property[i];
return result;
}
}, param );
}
protected T dispatchIntegerArrayProperty( final Integer[] property, K param )
{
return dispatchIntegerArrayProperty( new BoxedArray<int[], Integer>( property )
{
@Override
@SuppressWarnings( "boxing" )
public int[] getClonedArray()
{
int[] result = new int[property.length];
for ( int i = 0; i < result.length; i++ )
result[i] = property[i];
return result;
}
}, param );
}
protected T dispatchLongArrayProperty( final Long[] property, K param )
{
return dispatchLongArrayProperty( new BoxedArray<long[], Long>( property )
{
@Override
@SuppressWarnings( "boxing" )
public long[] getClonedArray()
{
long[] result = new long[property.length];
for ( int i = 0; i < result.length; i++ )
result[i] = property[i];
return result;
}
}, param );
}
protected T dispatchFloatArrayProperty( final Float[] property, K param )
{
return dispatchFloatArrayProperty( new BoxedArray<float[], Float>( property )
{
@Override
@SuppressWarnings( "boxing" )
public float[] getClonedArray()
{
float[] result = new float[property.length];
for ( int i = 0; i < result.length; i++ )
result[i] = property[i];
return result;
}
}, param );
}
protected T dispatchDoubleArrayProperty( final Double[] property, K param )
{
return dispatchDoubleArrayProperty( new BoxedArray<double[], Double>( property )
{
@Override
@SuppressWarnings( "boxing" )
public double[] getClonedArray()
{
double[] result = new double[property.length];
for ( int i = 0; i < result.length; i++ )
result[i] = property[i];
return result;
}
}, param );
}
protected T dispatchBooleanArrayProperty( final Boolean[] property, K param )
{
return dispatchBooleanArrayProperty( new BoxedArray<boolean[], Boolean>( property )
{
@Override
@SuppressWarnings( "boxing" )
public boolean[] getClonedArray()
{
boolean[] result = new boolean[property.length];
for ( int i = 0; i < result.length; i++ )
result[i] = property[i];
return result;
}
}, param );
}
protected abstract T dispatchStringProperty( String property, K param );
protected T dispatchStringArrayProperty( final String[] property, K param )
{
return dispatchStringArrayProperty( new BoxedArray<String[], String>( property )
{
@Override
public String[] getClonedArray()
{
return property.clone();
}
}, param );
}
protected T dispatchStringArrayProperty( PropertyArray<String[], String> array, K param )
{
return dispatchArray( array, param );
}
protected T dispatchByteArrayProperty( PropertyArray<byte[], Byte> array, K param )
{
return dispatchNumberArray( array, param );
}
protected T dispatchCharacterArrayProperty( PropertyArray<char[], Character> array, K param )
{
return dispatchArray( array, param );
}
protected T dispatchShortArrayProperty( PropertyArray<short[], Short> array, K param )
{
return dispatchNumberArray( array, param );
}
protected T dispatchIntegerArrayProperty( PropertyArray<int[], Integer> array, K param )
{
return dispatchNumberArray( array, param );
}
protected T dispatchLongArrayProperty( PropertyArray<long[], Long> array, K param )
{
return dispatchNumberArray( array, param );
}
protected T dispatchFloatArrayProperty( PropertyArray<float[], Float> array, K param )
{
return dispatchNumberArray( array, param );
}
protected T dispatchDoubleArrayProperty( PropertyArray<double[], Double> array, K param )
{
return dispatchNumberArray( array, param );
}
protected T dispatchBooleanArrayProperty( PropertyArray<boolean[], Boolean> array, K param )
{
return dispatchArray( array, param );
}
protected T dispatchNumberArray( PropertyArray<?, ? extends Number> array, K param )
{
return dispatchArray( array, param );
}
protected T dispatchArray( PropertyArray<?, ?> array, K param )
{
throw new UnsupportedOperationException( "Unhandled array type: " + array.getType() );
}
private static abstract class BoxedArray<A, T> extends PropertyArray<A, T>
{
private final T[] array;
BoxedArray( T[] array )
{
this.array = array;
}
@Override
public int length()
{
return array.length;
}
@Override
public Iterator<T> iterator()
{
return new ArrayIterator<T>( array );
}
@Override
public Class<?> getType()
{
return array.getClass();
}
}
private static abstract class PrimitiveArray<A, T> extends PropertyArray<A, T>
{
@Override
public Iterator<T> iterator()
{
return new Iterator<T>()
{
final int size = length();
int pos = 0;
@Override
public boolean hasNext()
{
return pos < size;
}
@Override
public T next()
{
return item( pos++ );
}
@Override
public void remove()
{
throw new UnsupportedOperationException(
"Cannot remove element from primitive array." );
}
};
}
protected abstract T item( int offset );
}
}
| false
|
community_server-api_src_main_java_org_neo4j_server_helpers_PropertyTypeDispatcher.java
|
2,323
|
{
@Override
public Logging create( Configurator configurator )
{
// Enough until the opposite is proven. This is only used by ServerBuilder,
// which in turn is only used by tests.
return DevNullLoggingService.DEV_NULL;
}
};
| false
|
community_server_src_test_java_org_neo4j_server_helpers_LoggingFactory.java
|
2,324
|
{
@Override
public Logging create( Configurator configurator )
{
return DefaultLogging.createDefaultLogging( configurator.getDatabaseTuningProperties() );
}
};
| false
|
community_server_src_test_java_org_neo4j_server_helpers_LoggingFactory.java
|
2,325
|
{
@Override
public Logging create( Configurator configurator )
{
return logging;
}
};
| false
|
community_server_src_test_java_org_neo4j_server_helpers_LoggingFactory.java
|
2,326
|
public abstract class LoggingFactory
{
public abstract Logging create( Configurator configurator );
public static LoggingFactory given( final Logging logging )
{
return new LoggingFactory()
{
@Override
public Logging create( Configurator configurator )
{
return logging;
}
};
}
public static final LoggingFactory DEFAULT_LOGGING = new LoggingFactory()
{
@Override
public Logging create( Configurator configurator )
{
return DefaultLogging.createDefaultLogging( configurator.getDatabaseTuningProperties() );
}
};
public static final LoggingFactory IMPERMANENT_LOGGING = new LoggingFactory()
{
@Override
public Logging create( Configurator configurator )
{
// Enough until the opposite is proven. This is only used by ServerBuilder,
// which in turn is only used by tests.
return DevNullLoggingService.DEV_NULL;
}
};
}
| false
|
community_server_src_test_java_org_neo4j_server_helpers_LoggingFactory.java
|
2,327
|
class ParameterExtractor extends DataExtractor
{
final String name;
final Class<?> type;
final boolean optional;
final String description;
final TypeCaster caster;
ParameterExtractor( TypeCaster caster, Class<?> type, Parameter param, Description description )
{
this.caster = caster;
this.type = type;
this.name = param.name();
this.optional = param.optional();
this.description = description == null ? "" : description.value();
}
@Override
Object extract( GraphDatabaseAPI graphDb, Object source, ParameterList parameters ) throws BadInputException
{
Object result = caster.get( graphDb, parameters, name );
if ( optional || result != null ) return result;
throw new IllegalArgumentException( "Mandatory argument \"" + name + "\" not supplied." );
}
@Override
void describe( ParameterDescriptionConsumer consumer )
{
consumer.describeParameter( name, type, optional, description );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_plugins_ParameterExtractor.java
|
2,328
|
{
@Override
String convert( GraphDatabaseAPI graphDb, Object value )
throws BadInputException
{
return convertString( value );
}
@Override
String[] newArray( int size )
{
return new String[size];
}
} );
| false
|
community_server-api_src_main_java_org_neo4j_server_plugins_ParameterList.java
|
2,329
|
public class JSONPrettifier
{
private static final Gson GSON = new GsonBuilder().setPrettyPrinting()
.create();
private static final JsonParser JSON_PARSER = new JsonParser();
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final ObjectWriter WRITER = MAPPER.writerWithDefaultPrettyPrinter();
public static String parse( final String json )
{
if ( json == null )
{
return "";
}
String result = json;
try
{
if ( json.contains( "\"exception\"" ) )
{
// the gson renderer is much better for stacktraces
result = gsonPrettyPrint( json );
}
else
{
result = jacksonPrettyPrint( json );
}
}
catch ( Exception e )
{
/*
* Enable the output to see where exceptions happen.
* We need to be able to tell the rest docs tools to expect
* a json parsing error from here, then we can simply throw an exception instead.
* (we have tests sending in broken json to test the response)
*/
// System.out.println( "***************************************" );
// System.out.println( json );
// System.out.println( "***************************************" );
}
return result;
}
private static String gsonPrettyPrint( final String json ) throws Exception
{
JsonElement element = JSON_PARSER.parse( json );
return GSON.toJson( element );
}
private static String jacksonPrettyPrint( final String json )
throws Exception
{
Object myObject = MAPPER.readValue( json, Object.class );
return WRITER.writeValueAsString( myObject );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_JSONPrettifier.java
|
2,330
|
{
@Override
public boolean run()
{
return true;
}
@Override
public String getFailureMessage()
{
return "blah blah";
}
};
| false
|
community_server_src_test_java_org_neo4j_server_preflight_TestPreflightTasks.java
|
2,331
|
public class TestPerformUpgradeIfNecessary
{
public static final String HOME_DIRECTORY = TargetDirectory.forTest( TestPerformUpgradeIfNecessary.class ).makeGraphDbDir().getAbsolutePath();
public static final String STORE_DIRECTORY = HOME_DIRECTORY + "/data/graph.db";
@Test
public void shouldExitImmediatelyIfStoreIsAlreadyAtLatestVersion() throws IOException
{
Configuration serverConfig = buildProperties( false );
new GraphDatabaseFactory().newEmbeddedDatabaseBuilder( STORE_DIRECTORY ).newGraphDatabase().shutdown();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PerformUpgradeIfNecessary upgrader = new PerformUpgradeIfNecessary( serverConfig,
loadNeo4jProperties(), new PrintStream( outputStream ), DEV_NULL );
boolean exit = upgrader.run();
assertEquals( true, exit );
assertEquals( "", new String( outputStream.toByteArray() ) );
}
@Test
public void shouldGiveHelpfulMessageIfAutoUpgradeParameterNotSet() throws IOException
{
Configuration serverProperties = buildProperties( false );
prepareSampleLegacyDatabase( new File( STORE_DIRECTORY ) );
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PerformUpgradeIfNecessary upgrader = new PerformUpgradeIfNecessary( serverProperties,
loadNeo4jProperties(), new PrintStream( outputStream ), DEV_NULL );
boolean exit = upgrader.run();
assertEquals( false, exit );
String[] lines = new String( outputStream.toByteArray() ).split( "\\r?\\n" );
assertThat( "'" + lines[0] + "' contains '" + "To enable automatic upgrade, please set configuration parameter " +
"\"allow_store_upgrade=true\"", lines[0].contains("To enable automatic upgrade, please set configuration parameter " +
"\"allow_store_upgrade=true\""), is(true) );
}
@Test
public void shouldExitCleanlyIfDatabaseMissingSoThatDatabaseCreationIsLeftToMainProcess() throws IOException
{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PerformUpgradeIfNecessary upgrader = new PerformUpgradeIfNecessary( buildProperties( true ),
loadNeo4jProperties(), new PrintStream( outputStream ), DEV_NULL );
boolean exit = upgrader.run();
assertEquals( true, exit );
assertEquals( "", new String( outputStream.toByteArray() ) );
}
@Test
public void shouldUpgradeDatabase() throws IOException
{
Configuration serverConfig = buildProperties( true );
prepareSampleLegacyDatabase( new File( STORE_DIRECTORY ) );
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PerformUpgradeIfNecessary upgrader = new PerformUpgradeIfNecessary( serverConfig,
loadNeo4jProperties(), new PrintStream( outputStream ), DEV_NULL );
boolean exit = upgrader.run();
assertEquals( true, exit );
String[] lines = new String( outputStream.toByteArray() ).split( "\\r?\\n" );
assertEquals( "Starting upgrade of database store files", lines[0] );
assertEquals( dots(100), lines[1] );
assertEquals( "Finished upgrade of database store files", lines[2] );
}
private Configuration buildProperties(boolean allowStoreUpgrade) throws IOException
{
FileUtils.deleteRecursively( new File( HOME_DIRECTORY ) );
new File( HOME_DIRECTORY + "/conf" ).mkdirs();
Properties databaseProperties = new Properties();
if (allowStoreUpgrade)
{
databaseProperties.setProperty( GraphDatabaseSettings.allow_store_upgrade.name(), "true" );
}
String databasePropertiesFileName = HOME_DIRECTORY + "/conf/neo4j.properties";
databaseProperties.store( new FileWriter( databasePropertiesFileName ), null );
Configuration serverProperties = new MapBasedConfiguration();
serverProperties.setProperty( Configurator.DATABASE_LOCATION_PROPERTY_KEY, STORE_DIRECTORY );
serverProperties.setProperty( Configurator.DB_TUNING_PROPERTY_FILE_KEY, databasePropertiesFileName );
return serverProperties;
}
private Map<String,String> loadNeo4jProperties() throws IOException
{
String databasePropertiesFileName = HOME_DIRECTORY + "/conf/neo4j.properties";
return MapUtil.load(new File(databasePropertiesFileName));
}
public static void prepareSampleLegacyDatabase( File workingDirectory ) throws IOException
{
File resourceDirectory = findOldFormatStoreDirectory();
deleteRecursively( workingDirectory );
assertTrue( workingDirectory.mkdirs() );
copyRecursively( resourceDirectory, workingDirectory );
}
public static File findOldFormatStoreDirectory()
{
URL legacyStoreResource = TestPerformUpgradeIfNecessary.class.getResource( "legacystore/exampledb/neostore" );
return new File( legacyStoreResource.getFile() ).getParentFile();
}
private String dots( int count )
{
StringBuilder builder = new StringBuilder();
for (int i = 0; i < count; i++) {
builder.append( "." );
}
return builder.toString();
}
}
| false
|
community_server_src_test_java_org_neo4j_server_preflight_TestPerformUpgradeIfNecessary.java
|
2,332
|
public class TestPerformRecoveryIfNecessary {
public static final String HOME_DIRECTORY = "target/" + TestPerformRecoveryIfNecessary.class.getSimpleName();
public static final String STORE_DIRECTORY = HOME_DIRECTORY + "/data/graph.db";
private static final String LINEBREAK = System.getProperty("line.separator");
@Test
public void shouldNotDoAnythingIfNoDBPresent() throws Exception
{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Configuration config = buildProperties();
PerformRecoveryIfNecessary task = new PerformRecoveryIfNecessary(config, new HashMap<String,String>(), new PrintStream(outputStream), DevNullLoggingService.DEV_NULL);
assertThat("Recovery task runs successfully.", task.run(), is(true));
assertThat("No database should have been created.", new File(STORE_DIRECTORY).exists(), is(false));
assertThat("Recovery task should not print anything.", outputStream.toString(), is(""));
}
@Test
public void doesNotPrintAnythingIfDatabaseWasCorrectlyShutdown() throws Exception
{
// Given
Configuration config = buildProperties();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
new GraphDatabaseFactory().newEmbeddedDatabase(STORE_DIRECTORY).shutdown();
PerformRecoveryIfNecessary task = new PerformRecoveryIfNecessary(config, new HashMap<String,String>(), new PrintStream(outputStream), DevNullLoggingService.DEV_NULL);
assertThat("Recovery task should run successfully.", task.run(), is(true));
assertThat("Database should exist.", new File(STORE_DIRECTORY).exists(), is(true));
assertThat("Recovery should not print anything.", outputStream.toString(), is(""));
}
@Test
public void shouldPerformRecoveryIfNecessary() throws Exception
{
// Given
StoreRecoverer recoverer = new StoreRecoverer();
Configuration config = buildProperties();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
new GraphDatabaseFactory().newEmbeddedDatabase(STORE_DIRECTORY).shutdown();
// Make this look incorrectly shut down
new File(STORE_DIRECTORY, "nioneo_logical.log.active").delete();
assertThat("Store should not be recovered", recoverer.recoveryNeededAt(new File(STORE_DIRECTORY), new HashMap<String,String>()),
is(true));
// Run recovery
PerformRecoveryIfNecessary task = new PerformRecoveryIfNecessary(config, new HashMap<String,String>(), new PrintStream(outputStream), DevNullLoggingService.DEV_NULL);
assertThat("Recovery task should run successfully.", task.run(), is(true));
assertThat("Database should exist.", new File(STORE_DIRECTORY).exists(), is(true));
assertThat("Recovery should print status message.", outputStream.toString(), is("Detected incorrectly shut down database, performing recovery.." + LINEBREAK));
assertThat("Store should be recovered", recoverer.recoveryNeededAt(new File(STORE_DIRECTORY), new HashMap<String,String>()),
is(false));
}
private Configuration buildProperties() throws IOException
{
FileUtils.deleteRecursively( new File( HOME_DIRECTORY ) );
new File( HOME_DIRECTORY + "/conf" ).mkdirs();
Properties databaseProperties = new Properties();
String databasePropertiesFileName = HOME_DIRECTORY + "/conf/neo4j.properties";
databaseProperties.store( new FileWriter( databasePropertiesFileName ), null );
Configuration serverProperties = new MapBasedConfiguration();
serverProperties.setProperty( Configurator.DATABASE_LOCATION_PROPERTY_KEY, STORE_DIRECTORY );
serverProperties.setProperty( Configurator.DB_TUNING_PROPERTY_FILE_KEY, databasePropertiesFileName );
return serverProperties;
}
}
| false
|
community_server_src_test_java_org_neo4j_server_preflight_TestPerformRecoveryIfNecessary.java
|
2,333
|
@SuppressWarnings( "serial" )
public class PreflightFailedException extends RuntimeException
{
public PreflightFailedException( PreflightTask task )
{
super( String.format( "Startup failed due to preflight task [%s]: %s", task.getClass(),
task.getFailureMessage() ) );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_preflight_PreflightFailedException.java
|
2,334
|
public class PreFlightTasks
{
private final PreflightTask[] tasks;
private final ConsoleLogger log;
private PreflightTask failedTask = null;
public PreFlightTasks( Logging logging, PreflightTask... tasks )
{
this.tasks = tasks;
this.log = logging.getConsoleLog( getClass() );
}
public boolean run()
{
if ( tasks == null || tasks.length < 1 )
{
return true;
}
for ( PreflightTask r : tasks )
{
if ( !r.run() )
{
log.error( r.getFailureMessage() );
failedTask = r;
return false;
}
}
return true;
}
public PreflightTask failedTask()
{
return failedTask;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_preflight_PreFlightTasks.java
|
2,335
|
public class PerformUpgradeIfNecessary implements PreflightTask
{
private String failureMessage = "Unable to upgrade database";
private final Configuration config;
private final PrintStream out;
private final Map<String, String> dbConfig;
private final ConsoleLogger log;
public PerformUpgradeIfNecessary( Configuration serverConfig, Map<String, String> dbConfig, PrintStream out,
Logging logging )
{
this.config = serverConfig;
this.dbConfig = dbConfig;
this.out = out;
this.log = logging.getConsoleLog( getClass() );
}
@Override
public boolean run()
{
try
{
String dbLocation = new File( config.getString( Configurator.DATABASE_LOCATION_PROPERTY_KEY ) )
.getAbsolutePath();
if ( new CurrentDatabase(new StoreVersionCheck( new DefaultFileSystemAbstraction() ) ).storeFilesAtCurrentVersion( new File( dbLocation ) ) )
{
return true;
}
File store = new File( dbLocation, NeoStore.DEFAULT_NAME);
dbConfig.put( "store_dir", dbLocation );
dbConfig.put( "neo_store", store.getPath() );
FileSystemAbstraction fileSystem = new DefaultFileSystemAbstraction();
UpgradableDatabase upgradableDatabase = new UpgradableDatabase( new StoreVersionCheck( fileSystem ) );
if ( !upgradableDatabase.storeFilesUpgradeable( store ) )
{
return true;
}
Config conf = new Config( dbConfig, GraphDatabaseSettings.class );
StoreUpgrader storeUpgrader = new StoreUpgrader( conf,
new ConfigMapUpgradeConfiguration( conf ),
upgradableDatabase, new StoreMigrator( new VisibleMigrationProgressMonitor( StringLogger.DEV_NULL, out ) ),
new DatabaseFiles( fileSystem ), new DefaultIdGeneratorFactory(), fileSystem );
try
{
storeUpgrader.attemptUpgrade( store );
}
catch ( UpgradeNotAllowedByConfigurationException e )
{
log.log( e.getMessage() );
out.println( e.getMessage() );
failureMessage = e.getMessage();
return false;
}
catch ( StoreUpgrader.UnableToUpgradeException e )
{
log.error( "Unable to upgrade store", e );
return false;
}
return true;
}
catch ( Exception e )
{
log.error( "Unknown error", e );
return false;
}
}
@Override
public String getFailureMessage()
{
return failureMessage;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_preflight_PerformUpgradeIfNecessary.java
|
2,336
|
public class PerformRecoveryIfNecessary implements PreflightTask
{
private final String failureMessage = "Unable to recover database";
private final Configuration config;
private final PrintStream out;
private final Map<String, String> dbConfig;
private final ConsoleLogger log;
public PerformRecoveryIfNecessary( Configuration serverConfig, Map<String, String> dbConfig, PrintStream out,
Logging logging )
{
this.config = serverConfig;
this.dbConfig = dbConfig;
this.out = out;
this.log = logging.getConsoleLog( getClass() );
}
@Override
public boolean run()
{
try
{
File dbLocation = new File( config.getString( Configurator.DATABASE_LOCATION_PROPERTY_KEY ) );
if ( dbLocation.exists() )
{
StoreRecoverer recoverer = new StoreRecoverer();
if ( recoverer.recoveryNeededAt( dbLocation, dbConfig ) )
{
out.println( "Detected incorrectly shut down database, performing recovery.." );
recoverer.recover( dbLocation, dbConfig );
}
}
return true;
}
catch ( IOException e )
{
log.error( "Recovery startup task failed.", e );
return false;
}
}
@Override
public String getFailureMessage()
{
return failureMessage;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_preflight_PerformRecoveryIfNecessary.java
|
2,337
|
public class HTTPLoggingPreparednessRuleTest
{
@Test
public void shouldPassWhenExplicitlyDisabled()
{
// given
Configuration config = new MapBasedConfiguration();
config.setProperty( Configurator.HTTP_LOGGING, "false" );
EnsurePreparedForHttpLogging rule = new EnsurePreparedForHttpLogging(config);
// when
boolean result = rule.run( );
// then
assertTrue( result );
assertEquals( StringUtils.EMPTY, rule.getFailureMessage() );
}
@Test
public void shouldPassWhenImplicitlyDisabled()
{
// given
Configuration config = new MapBasedConfiguration();
EnsurePreparedForHttpLogging rule = new EnsurePreparedForHttpLogging(config);
// when
boolean result = rule.run( );
// then
assertTrue( result );
assertEquals( StringUtils.EMPTY, rule.getFailureMessage() );
}
@Test
public void shouldPassWhenEnabledWithGoodConfigSpecified() throws Exception
{
// given
final File logDir = TargetDirectory.forTest( this.getClass() ).cleanDirectory( "logDir" );
final File confDir = TargetDirectory.forTest( this.getClass() ).cleanDirectory( "confDir" );
Configuration config = new MapBasedConfiguration();
config.setProperty( Configurator.HTTP_LOGGING, "true" );
config.setProperty( Configurator.HTTP_LOG_CONFIG_LOCATION,
createConfigFile( createLogbackConfigXml( logDir ), confDir ).getAbsolutePath() );
EnsurePreparedForHttpLogging rule = new EnsurePreparedForHttpLogging(config);
// when
boolean result = rule.run( );
// then
assertTrue( result );
assertEquals( StringUtils.EMPTY, rule.getFailureMessage() );
}
@Test
public void shouldFailWhenEnabledWithUnwritableLogDirSpecifiedInConfig() throws Exception
{
// given
final File confDir = TargetDirectory.forTest( this.getClass() ).cleanDirectory( "confDir" );
Configuration config = new MapBasedConfiguration();
config.setProperty( Configurator.HTTP_LOGGING, "true" );
final File unwritableDirectory = createUnwritableDirectory();
config.setProperty( Configurator.HTTP_LOG_CONFIG_LOCATION,
createConfigFile( createLogbackConfigXml( unwritableDirectory ), confDir ).getAbsolutePath() );
EnsurePreparedForHttpLogging rule = new EnsurePreparedForHttpLogging(config);
// when
boolean result = rule.run( );
// then
assertFalse( result );
assertEquals(
String.format( "HTTP log directory [%s] does not exist", unwritableDirectory ),
rule.getFailureMessage() );
}
public static File createUnwritableDirectory()
{
File file;
if ( osIsWindows() )
{
file = new File( "\\\\" + UUID.randomUUID().toString() + "\\" );
}
else if ( osIsMacOS() )
{
file = new File( "/Network/Servers/localhost/" + UUID.randomUUID().toString() );
}
else
{
file = new File( "/proc/" + UUID.randomUUID().toString() + "/random");
}
return file;
}
public static File createConfigFile( String configXml, File location ) throws IOException
{
final File configFile = new File( location.getAbsolutePath() + File.separator + "neo4j-logback-config.xml" );
FileOutputStream fos = new FileOutputStream( configFile );
fos.write( configXml.getBytes() );
fos.close();
return configFile;
}
public static String createLogbackConfigXml( File logDirectory )
{
return "<configuration>\n" +
" <appender name=\"FILE\" class=\"ch.qos.logback.core.rolling.RollingFileAppender\">\n" +
" <file>" + logDirectory.getAbsolutePath() + File.separator + "http.log</file>\n" +
" <rollingPolicy class=\"ch.qos.logback.core.rolling.TimeBasedRollingPolicy\">\n" +
" <fileNamePattern>" + logDirectory.getAbsolutePath() + File.separator + "http.%d{yyyy-MM-dd_HH}.log</fileNamePattern>\n" +
" <maxHistory>30</maxHistory>\n" +
" </rollingPolicy>\n" +
"\n" +
" <encoder>\n" +
" <!-- Note the deliberate misspelling of \"referer\" in accordance with RFC 2616 -->\n" +
" <pattern>%h %l %user [%t{dd/MMM/yyyy:HH:mm:ss Z}] \"%r\" %s %b \"%i{Referer}\" \"%i{User-Agent}\"</pattern>\n" +
" </encoder>\n" +
" </appender>\n" +
"\n" +
" <appender-ref ref=\"FILE\" />\n" +
"</configuration>";
}
}
| false
|
community_server_src_test_java_org_neo4j_server_preflight_HTTPLoggingPreparednessRuleTest.java
|
2,338
|
public class EnsurePreparedForHttpLogging implements PreflightTask
{
private String failureMessage = "";
private Configuration config;
public EnsurePreparedForHttpLogging(Configuration config)
{
this.config = config;
}
@Override
public boolean run()
{
boolean enabled = config.getBoolean( Configurator.HTTP_LOGGING, Configurator.DEFAULT_HTTP_LOGGING );
if ( !enabled )
{
return true;
}
File logLocation = extractLogLocationFromConfig(config.getString( Configurator.HTTP_LOG_CONFIG_LOCATION ) );
if ( logLocation != null )
{
if ( validateFileBasedLoggingConfig( logLocation ) )
{
return true;
}
else
{
return false;
}
}
else
{
// File logging is not configured, no other logging can be easily checked here
return true;
}
}
private boolean validateFileBasedLoggingConfig( File logLocation )
{
try
{
FileUtils.forceMkdir( logLocation );
}
catch ( IOException e )
{
failureMessage = String.format( "HTTP log directory [%s] does not exist",
logLocation.getAbsolutePath() );
return false;
}
if ( !logLocation.exists() )
{
failureMessage = String.format( "HTTP log directory [%s] cannot be created",
logLocation.getAbsolutePath() );
return false;
}
if ( !logLocation.canWrite() )
{
failureMessage = String.format( "HTTP log directory [%s] is not writable",
logLocation.getAbsolutePath() );
return false;
}
return true;
}
private File extractLogLocationFromConfig( String configLocation )
{
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
try
{
final File file = new File( configLocation );
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse( file );
final Node node = doc.getElementsByTagName( "file" ).item( 0 );
return new File( node.getTextContent() ).getParentFile();
}
catch ( Exception e )
{
return null;
}
}
@Override
public String getFailureMessage()
{
return failureMessage;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_preflight_EnsurePreparedForHttpLogging.java
|
2,339
|
public class EnsureNeo4jPropertiesExist implements PreflightTask
{
private static final String EMPTY_STRING = "";
private boolean passed = false;
private boolean ran = false;
protected String failureMessage = EMPTY_STRING;
private Configuration config;
public EnsureNeo4jPropertiesExist(Configuration config)
{
this.config = config;
}
@Override
public boolean run()
{
ran = true;
String configFilename = config.getString( Configurator.NEO_SERVER_CONFIG_FILE_KEY );
if(configFilename == null)
{
failureMessage = String.format( "No server configuration file set, unable to load configuration. Expected system property '%s' to point to config file.", Configurator.NEO_SERVER_CONFIG_FILE_KEY );
return false;
}
Properties configProperties = new Properties();
FileInputStream inputStream = null;
try
{
inputStream = new FileInputStream( configFilename );
configProperties.load( inputStream );
}
catch ( IOException e )
{
failureMessage = String.format( "Failed to load configuration properties from [%s]", configFilename );
return false;
}
finally
{
if ( inputStream != null )
{
try
{
inputStream.close();
}
catch ( IOException e )
{ // Couldn't close it
}
}
}
passed = validateProperties( configProperties );
return passed;
}
protected boolean validateProperties( Properties configProperties )
{
// default implementation: all OK
return true;
}
@Override
public String getFailureMessage()
{
if ( passed )
{
return EMPTY_STRING;
}
if ( !ran )
{
return String.format( "%s has not been run", getClass().getName() );
}
else
{
return failureMessage;
}
}
}
| false
|
community_server_src_main_java_org_neo4j_server_preflight_EnsureNeo4jPropertiesExist.java
|
2,340
|
class UriTypeCaster extends TypeCaster
{
@Override
Object get( GraphDatabaseAPI graphDb, ParameterList parameters, String name ) throws BadInputException
{
return parameters.getUri( name );
}
@Override
Object[] getList( GraphDatabaseAPI graphDb, ParameterList parameters, String name ) throws BadInputException
{
return parameters.getUriList( name );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_plugins_UriTypeCaster.java
|
2,341
|
class URLTypeCaster extends TypeCaster
{
@Override
Object get( GraphDatabaseAPI graphDb, ParameterList parameters, String name ) throws BadInputException
{
try
{
return parameters.getUri( name )
.toURL();
}
catch ( MalformedURLException e )
{
throw new BadInputException( e );
}
}
@Override
Object[] getList( GraphDatabaseAPI graphDb, ParameterList parameters, String name ) throws BadInputException
{
URI[] uris = parameters.getUriList( name );
URL[] urls = new URL[uris.length];
try
{
for ( int i = 0; i < urls.length; i++ )
{
urls[i] = uris[i].toURL();
}
}
catch ( MalformedURLException e )
{
throw new BadInputException( e );
}
return urls;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_plugins_URLTypeCaster.java
|
2,342
|
abstract class TypeCaster
{
abstract Object get( GraphDatabaseAPI graphDb, ParameterList parameters, String name )
throws BadInputException;
Object convert( Object[] result ) throws BadInputException
{
throw new BadInputException( "Cannot convert to primitive array: " + result );
}
abstract Object[] getList( GraphDatabaseAPI graphDb, ParameterList parameters, String name )
throws BadInputException;
}
| false
|
community_server_src_main_java_org_neo4j_server_plugins_TypeCaster.java
|
2,343
|
class StringTypeCaster extends TypeCaster
{
@Override
Object get( GraphDatabaseAPI graphDb, ParameterList parameters, String name ) throws BadInputException
{
return parameters.getString( name );
}
@Override
Object[] getList( GraphDatabaseAPI graphDb, ParameterList parameters, String name ) throws BadInputException
{
return parameters.getStringList( name );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_plugins_StringTypeCaster.java
|
2,344
|
class SourceExtractor extends DataExtractor
{
SourceExtractor( Source source, Description description )
{
}
@Override
Object extract( GraphDatabaseAPI graphDb, Object source, ParameterList parameters )
{
return source;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_plugins_SourceExtractor.java
|
2,345
|
class ShortTypeCaster extends TypeCaster
{
@Override
Object get( GraphDatabaseAPI graphDb, ParameterList parameters, String name ) throws BadInputException
{
return parameters.getShort( name );
}
@Override
Object[] getList( GraphDatabaseAPI graphDb, ParameterList parameters, String name ) throws BadInputException
{
return parameters.getShortList( name );
}
@Override
@SuppressWarnings( "boxing" )
short[] convert( Object[] data ) throws BadInputException
{
Short[] incoming = (Short[]) data;
short[] result = new short[incoming.length];
for ( int i = 0; i < result.length; i++ )
{
result[i] = incoming[i];
}
return result;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_plugins_ShortTypeCaster.java
|
2,346
|
public abstract class ServerPlugin
{
final String name;
/**
* Create a server extension with the specified name.
*
* @param name the name of this extension.
*/
public ServerPlugin( String name )
{
this.name = verifyName( name );
}
/**
* Create a server extension using the simple name of the concrete class
* that extends {@link ServerPlugin} as the name for the extension.
*/
public ServerPlugin()
{
this.name = verifyName( getClass().getSimpleName() );
}
static String verifyName( String name )
{
if ( name == null )
{
throw new IllegalArgumentException( "Name may not be null" );
}
try
{
if ( !URLEncoder.encode( name, "UTF-8" ).equals( name ) )
{
throw new IllegalArgumentException( "Name contains illegal characters" );
}
} catch ( UnsupportedEncodingException e )
{
throw new Error( "UTF-8 should be supported", e );
}
return name;
}
@Override
public String toString()
{
return "ServerPlugin[" + name + "]";
}
static Iterable<ServerPlugin> load()
{
return Service.load( ServerPlugin.class );
}
/**
* Loads the extension points of this server extension. Override this method
* to provide your own, custom way of loading extension points. The default
* implementation loads {@link PluginPoint} based on methods with the
* {@link PluginTarget} annotation.
*
* @param extender the collection of {@link org.neo4j.server.plugins.PluginPoint}s for this
* {@link org.neo4j.server.plugins.ServerPlugin}.
*
*/
protected void loadServerExtender( ServerExtender extender )
{
for ( PluginPoint plugin : getDefaultExtensionPoints( extender.getPluginPointFactory() ) )
{
extender.addExtension( plugin.forType(), plugin );
}
}
/**
* Loads the extension points of this server extension. Override this method
* to provide your own, custom way of loading extension points. The default
* implementation loads {@link PluginPoint} based on methods with the
* {@link PluginTarget} annotation.
*
* @return the collection of {@link PluginPoint}s for this
* {@link ServerPlugin}.
*/
protected Collection<PluginPoint> getDefaultExtensionPoints( PluginPointFactory pluginPointFactory )
{
List<PluginPoint> result = new ArrayList<PluginPoint>();
for ( Method method : getClass().getMethods() )
{
PluginTarget target = method.getAnnotation( PluginTarget.class );
if ( target != null )
{
result.add( pluginPointFactory.createFrom( this, method, target.value() ) );
}
}
return result;
}
}
| false
|
community_server-api_src_main_java_org_neo4j_server_plugins_ServerPlugin.java
|
2,347
|
{
@Override
protected Iterator<PluginPoint> createNestedIterator(
Map<String, PluginPoint> item )
{
return item.values().iterator();
}
};
| false
|
community_server-api_src_main_java_org_neo4j_server_plugins_ServerExtender.java
|
2,348
|
public final class ServerExtender
{
@SuppressWarnings( "unchecked" )
private final Map<Class<?>, Map<String, PluginPoint>> targetToPluginMap = new HashMap();
private PluginPointFactory pluginPointFactory;
ServerExtender( PluginPointFactory pluginPointFactory )
{
this.pluginPointFactory = pluginPointFactory;
targetToPluginMap.put( Node.class, new ConcurrentHashMap<String, PluginPoint>() );
targetToPluginMap.put( Relationship.class, new ConcurrentHashMap<String, PluginPoint>() );
targetToPluginMap.put( GraphDatabaseService.class, new ConcurrentHashMap<String, PluginPoint>() );
}
Iterable<PluginPoint> getExtensionsFor( Class<?> type )
{
Map<String, PluginPoint> ext = targetToPluginMap.get( type );
if ( ext == null ) return Collections.emptyList();
return ext.values();
}
Iterable<PluginPoint> all()
{
return new NestingIterable<PluginPoint, Map<String, PluginPoint>>(
targetToPluginMap.values() )
{
@Override
protected Iterator<PluginPoint> createNestedIterator(
Map<String, PluginPoint> item )
{
return item.values().iterator();
}
};
}
PluginPoint getExtensionPoint( Class<?> type, String method )
throws PluginLookupException
{
Map<String, PluginPoint> ext = targetToPluginMap.get( type );
PluginPoint plugin = null;
if ( ext != null )
{
plugin = ext.get( method );
}
if ( plugin == null )
{
throw new PluginLookupException( "No plugin \"" + method + "\" for " + type );
}
return plugin;
}
void addExtension( Class<?> type, PluginPoint plugin )
{
Map<String, PluginPoint> ext = targetToPluginMap.get( type );
if ( ext == null ) throw new IllegalStateException( "Cannot extend " + type );
add( ext, plugin );
}
public void addGraphDatabaseExtensions( PluginPoint plugin )
{
add( targetToPluginMap.get( GraphDatabaseService.class ), plugin );
}
public void addNodeExtensions( PluginPoint plugin )
{
add( targetToPluginMap.get( Node.class ), plugin );
}
public void addRelationshipExtensions( PluginPoint plugin )
{
add( targetToPluginMap.get( Relationship.class ), plugin );
}
private static void add( Map<String, PluginPoint> extensions, PluginPoint plugin )
{
if ( extensions.get( plugin.name() ) != null )
{
throw new IllegalArgumentException(
"This plugin already has an plugin point with the name \""
+ plugin.name() + "\"" );
}
extensions.put( plugin.name(), plugin );
}
public PluginPointFactory getPluginPointFactory()
{
return pluginPointFactory;
}
}
| false
|
community_server-api_src_main_java_org_neo4j_server_plugins_ServerExtender.java
|
2,349
|
private static abstract class ValueResult extends ResultConverter
{
private final RepresentationType type;
ValueResult( RepresentationType type )
{
this.type = type;
}
@Override
final RepresentationType type()
{
return type;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_plugins_ResultConverter.java
|
2,350
|
public class TestPreflightTasks
{
@Test
public void shouldPassWithNoRules()
{
PreFlightTasks check = new PreFlightTasks( DEV_NULL );
assertTrue( check.run() );
}
@Test
public void shouldRunAllHealthChecksToCompletionIfNonFail()
{
PreFlightTasks check = new PreFlightTasks( DEV_NULL, getPassingRules() );
assertTrue( check.run() );
}
@Test
public void shouldFailIfOneOrMoreHealthChecksFail()
{
PreFlightTasks check = new PreFlightTasks( DEV_NULL, getWithOneFailingRule() );
assertFalse( check.run() );
}
@Test
public void shouldLogFailedRule()
{
Logging logging = new BufferingLogging();
PreFlightTasks check = new PreFlightTasks( logging, getWithOneFailingRule() );
check.run();
// Previously we tested on "SEVERE: blah blah" but that's a string
// depending
// on the regional settings of the OS.
assertThat( logging.toString(), containsString( "blah blah" ) );
}
@Test
public void shouldAdvertiseFailedRule()
{
PreFlightTasks check = new PreFlightTasks( DEV_NULL, getWithOneFailingRule() );
check.run();
assertNotNull( check.failedTask() );
}
private PreflightTask[] getWithOneFailingRule()
{
PreflightTask[] rules = new PreflightTask[5];
for ( int i = 0; i < rules.length; i++ )
{
rules[i] = new PreflightTask()
{
@Override
public boolean run()
{
return true;
}
@Override
public String getFailureMessage()
{
return "blah blah";
}
};
}
rules[rules.length / 2] = new PreflightTask()
{
@Override
public boolean run()
{
return false;
}
@Override
public String getFailureMessage()
{
return "blah blah";
}
};
return rules;
}
private PreflightTask[] getPassingRules()
{
PreflightTask[] rules = new PreflightTask[5];
for ( int i = 0; i < rules.length; i++ )
{
rules[i] = new PreflightTask()
{
@Override
public boolean run()
{
return true;
}
@Override
public String getFailureMessage()
{
return "blah blah";
}
};
}
return rules;
}
@Rule
public Mute mute = muteAll();
}
| false
|
community_server_src_test_java_org_neo4j_server_preflight_TestPreflightTasks.java
|
2,351
|
{
@Override
public boolean run()
{
return false;
}
@Override
public String getFailureMessage()
{
return "blah blah";
}
};
| false
|
community_server_src_test_java_org_neo4j_server_preflight_TestPreflightTasks.java
|
2,352
|
private static class ListResult extends ResultConverter
{
private final ResultConverter itemConverter;
ListResult( ResultConverter itemConverter )
{
this.itemConverter = itemConverter;
}
@Override
@SuppressWarnings( "unchecked" )
Representation convert( Object obj )
{
return new ListRepresentation( itemConverter.type(), new IterableWrapper<Representation, Object>(
(Iterable<Object>) obj )
{
@Override
protected Representation underlyingObjectToObject( Object object )
{
return itemConverter.convert( object );
}
} );
}
@Override
RepresentationType type()
{
return null;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_plugins_ResultConverter.java
|
2,353
|
{
@Override
public boolean run()
{
return true;
}
@Override
public String getFailureMessage()
{
return "blah blah";
}
};
| false
|
community_server_src_test_java_org_neo4j_server_preflight_TestPreflightTasks.java
|
2,354
|
public class IndexNodeDocIT extends AbstractRestFunctionalTestBase
{
private static FunctionalTestHelper functionalTestHelper;
private static GraphDbHelper helper;
@BeforeClass
public static void setupServer()
{
functionalTestHelper = new FunctionalTestHelper( server() );
helper = functionalTestHelper.getGraphDbHelper();
}
@Before
public void cleanTheDatabase()
{
cleanDatabase();
gen().setGraph( server().getDatabase().getGraph() );
}
long createNode()
{
GraphDatabaseAPI graphdb = server().getDatabase().getGraph();
try ( Transaction tx = graphdb.beginTx() )
{
Node node = graphdb.createNode();
tx.success();
return node.getId();
}
}
/**
* List node indexes.
*/
@Documented
@Test
public void shouldGetListOfNodeIndexesWhenOneExist() throws PropertyValueException
{
String indexName = "favorites";
helper.createNodeIndex( indexName );
String entity = gen().noGraph()
.expectedStatus( 200 )
.get( functionalTestHelper.nodeIndexUri() )
.entity();
Map<String, Object> map = JsonHelper.jsonToMap( entity );
assertNotNull( map.get( indexName ) );
assertEquals( "Was: " + map + ", no-auto-index:" + functionalTestHelper.removeAnyAutoIndex( map ), 1, functionalTestHelper.removeAnyAutoIndex( map ).size() );
}
/**
* Create node index
*
* NOTE: Instead of creating the index this way, you can simply start to use
* it, and it will be created automatically with default configuration.
*/
@Documented
@Test
public void shouldCreateANamedNodeIndex()
{
String indexName = "favorites";
int expectedIndexes = helper.getNodeIndexes().length + 1;
Map<String, String> indexSpecification = new HashMap<>();
indexSpecification.put( "name", indexName );
gen().noGraph()
.payload( JsonHelper.createJsonFrom( indexSpecification ) )
.expectedStatus( 201 )
.expectedHeader( "Location" )
.post( functionalTestHelper.nodeIndexUri() );
assertEquals( expectedIndexes, helper.getNodeIndexes().length );
assertThat( helper.getNodeIndexes(), FunctionalTestHelper.arrayContains( indexName ) );
}
@Test
public void shouldCreateANamedNodeIndexWithSpaces()
{
String indexName = "favorites with spaces";
int expectedIndexes = helper.getNodeIndexes().length + 1;
Map<String, String> indexSpecification = new HashMap<>();
indexSpecification.put( "name", indexName );
gen()
.payload( JsonHelper.createJsonFrom( indexSpecification ) )
.expectedStatus( 201 )
.expectedHeader( "Location" )
.post( functionalTestHelper.nodeIndexUri() );
assertEquals( expectedIndexes, helper.getNodeIndexes().length );
assertThat( helper.getNodeIndexes(), FunctionalTestHelper.arrayContains( indexName ) );
}
/**
* Create node index with configuration. This request is only necessary if
* you want to customize the index settings. If you are happy with the
* defaults, you can just start indexing nodes/relationships, as
* non-existent indexes will automatically be created as you do. See
* <<indexing-create-advanced>> for more information on index configuration.
*/
@Documented
@Test
public void shouldCreateANamedNodeIndexWithConfiguration() throws Exception
{
int expectedIndexes = helper.getNodeIndexes().length+1;
gen().noGraph()
.payload( "{\"name\":\"fulltext\", \"config\":{\"type\":\"fulltext\",\"provider\":\"lucene\"}}" )
.expectedStatus( 201 )
.expectedHeader( "Location" )
.post( functionalTestHelper.nodeIndexUri() );
assertEquals( expectedIndexes, helper.getNodeIndexes().length );
assertThat( helper.getNodeIndexes(), FunctionalTestHelper.arrayContains( "fulltext" ) );
}
/**
* Add node to index.
*
* Associates a node with the given key/value pair in the given index.
*
* NOTE: Spaces in the URI have to be encoded as +%20+.
*
* CAUTION: This does *not* overwrite previous entries. If you index the
* same key/value/item combination twice, two index entries are created. To
* do update-type operations, you need to delete the old entry before adding
* a new one.
*/
@Documented
@Test
public void shouldAddToIndex() throws Exception
{
final String indexName = "favorites";
final String key = "some-key";
final String value = "some value";
long nodeId = createNode();
// implicitly create the index
gen().noGraph()
.expectedStatus( 201 )
.payload(
JsonHelper.createJsonFrom( generateNodeIndexCreationPayload( key, value,
functionalTestHelper.nodeUri( nodeId ) ) ) )
.post( functionalTestHelper.indexNodeUri( indexName ) );
// look if we get one entry back
JaxRsResponse response = RestRequest.req().get(
functionalTestHelper.indexNodeUri( indexName, key,
URIHelper.encode( value ) ) );
String entity = response.getEntity();
Collection<?> hits = (Collection<?>) JsonHelper.jsonToSingleValue( entity );
assertEquals( 1, hits.size() );
}
private Object generateNodeIndexCreationPayload( String key, String value, String nodeUri )
{
Map<String, String> results = new HashMap<>();
results.put( "key", key );
results.put( "value", value );
results.put( "uri", nodeUri );
return results;
}
/**
* Find node by exact match.
*
* NOTE: Spaces in the URI have to be encoded as +%20+.
*/
@Documented
@Test
public void shouldAddToIndexAndRetrieveItByExactMatch() throws Exception
{
String indexName = "favorites";
String key = "key";
String value = "the value";
long nodeId = createNode();
value = URIHelper.encode( value );
// implicitly create the index
JaxRsResponse response = RestRequest.req()
.post( functionalTestHelper.indexNodeUri( indexName ), createJsonStringFor( nodeId, key, value ) );
assertEquals( 201, response.getStatus() );
// search it exact
String entity = gen().noGraph()
.expectedStatus( 200 )
.get( functionalTestHelper.indexNodeUri( indexName, key, URIHelper.encode( value ) ) )
.entity();
Collection<?> hits = (Collection<?>) JsonHelper.jsonToSingleValue( entity );
assertEquals( 1, hits.size() );
}
/**
* Find node by query.
*
* The query language used here depends on what type of index you are
* querying. The default index type is Lucene, in which case you should use
* the Lucene query language here. Below an example of a fuzzy search over
* multiple keys.
*
* See: {lucene-base-uri}/queryparsersyntax.html
*
* Getting the results with a predefined ordering requires adding the
* parameter
*
* `order=ordering`
*
* where ordering is one of index, relevance or score. In this case an
* additional field will be added to each result, named score, that holds
* the float value that is the score reported by the query result.
*/
@Documented
@Test
public void shouldAddToIndexAndRetrieveItByQuery() throws PropertyValueException
{
String indexName = "bobTheIndex";
String key = "Name";
String value = "Builder";
long node = helper.createNode( MapUtil.map( key, value ) );
helper.addNodeToIndex( indexName, key, value, node );
helper.addNodeToIndex( indexName, "Gender", "Male", node );
String entity = gen().noGraph()
.expectedStatus( 200 )
.get( functionalTestHelper.indexNodeUri( indexName ) + "?query=Name:Build~0.1%20AND%20Gender:Male" )
.entity();
Collection<?> hits = (Collection<?>) JsonHelper.jsonToSingleValue( entity );
assertEquals( 1, hits.size() );
LinkedHashMap<String, String> nodeMap = (LinkedHashMap) hits.iterator().next();
assertNull( "score should not be present when not explicitly ordering",
nodeMap.get( "score" ) );
}
@Test
public void orderedResultsAreSupersetOfUnordered() throws Exception
{
// Given
String indexName = "bobTheIndex";
String key = "Name";
String value = "Builder";
long node = helper.createNode( MapUtil.map( key, value ) );
helper.addNodeToIndex( indexName, key, value, node );
helper.addNodeToIndex( indexName, "Gender", "Male", node );
String entity = gen().expectedStatus( 200 ).get(
functionalTestHelper.indexNodeUri( indexName )
+ "?query=Name:Build~0.1%20AND%20Gender:Male" ).entity();
Collection<?> hits = (Collection<?>) JsonHelper.jsonToSingleValue( entity );
LinkedHashMap<String, String> nodeMapUnordered = (LinkedHashMap) hits.iterator().next();
// When
entity = gen().expectedStatus( 200 ).get(
functionalTestHelper.indexNodeUri( indexName )
+ "?query=Name:Build~0.1%20AND%20Gender:Male&order=score" ).entity();
hits = (Collection<?>) JsonHelper.jsonToSingleValue( entity );
LinkedHashMap<String, String> nodeMapOrdered = (LinkedHashMap) hits.iterator().next();
// Then
for ( Map.Entry<String, String> unorderedEntry : nodeMapUnordered.entrySet() )
{
assertEquals( "wrong entry for key: " + unorderedEntry.getKey(),
unorderedEntry.getValue(),
nodeMapOrdered.get( unorderedEntry.getKey() ) );
}
assertTrue( "There should be only one extra value for the ordered map",
nodeMapOrdered.size() == nodeMapUnordered.size() + 1 );
}
@Test
public void shouldAddToIndexAndRetrieveItByQuerySorted()
throws PropertyValueException
{
String indexName = "bobTheIndex";
String key = "Name";
long node1 = helper.createNode();
long node2 = helper.createNode();
helper.addNodeToIndex( indexName, key, "Builder2", node1 );
helper.addNodeToIndex( indexName, "Gender", "Male", node1 );
helper.addNodeToIndex( indexName, key, "Builder", node2 );
helper.addNodeToIndex( indexName, "Gender", "Male", node2 );
String entity = gen().expectedStatus( 200 ).get(
functionalTestHelper.indexNodeUri( indexName )
+ "?query=Name:Build~0.1%20AND%20Gender:Male&order=relevance" ).entity();
Collection<?> hits = (Collection<?>) JsonHelper.jsonToSingleValue( entity );
assertEquals( 2, hits.size() );
Iterator<LinkedHashMap<String, Object>> it = (Iterator<LinkedHashMap<String, Object>>) hits.iterator();
LinkedHashMap<String, Object> node2Map = it.next();
LinkedHashMap<String, Object> node1Map = it.next();
float score2 = ( (Double) node2Map.get( "score" ) ).floatValue();
float score1 = ( (Double) node1Map.get( "score" ) ).floatValue();
assertTrue(
"results returned in wrong order for relevance ordering",
( (String) node2Map.get( "self" ) ).endsWith( Long.toString( node2 ) ) );
assertTrue(
"results returned in wrong order for relevance ordering",
( (String) node1Map.get( "self" ) ).endsWith( Long.toString( node1 ) ) );
/*
* scores are always the same, just the ordering changes. So all subsequent tests will
* check the same condition.
*/
assertTrue( "scores are reversed", score2 > score1 );
entity = gen().expectedStatus( 200 ).get(
functionalTestHelper.indexNodeUri( indexName )
+ "?query=Name:Build~0.1%20AND%20Gender:Male&order=index" ).entity();
hits = (Collection<?>) JsonHelper.jsonToSingleValue( entity );
assertEquals( 2, hits.size() );
it = (Iterator<LinkedHashMap<String, Object>>) hits.iterator();
/*
* index order, so as they were added
*/
node1Map = it.next();
node2Map = it.next();
score1 = ( (Double) node1Map.get( "score" ) ).floatValue();
score2 = ( (Double) node2Map.get( "score" ) ).floatValue();
assertTrue(
"results returned in wrong order for index ordering",
( (String) node1Map.get( "self" ) ).endsWith( Long.toString( node1 ) ) );
assertTrue(
"results returned in wrong order for index ordering",
( (String) node2Map.get( "self" ) ).endsWith( Long.toString( node2 ) ) );
assertTrue( "scores are reversed", score2 > score1 );
entity = gen().expectedStatus( 200 ).get(
functionalTestHelper.indexNodeUri( indexName )
+ "?query=Name:Build~0.1%20AND%20Gender:Male&order=score" ).entity();
hits = (Collection<?>) JsonHelper.jsonToSingleValue( entity );
assertEquals( 2, hits.size() );
it = (Iterator<LinkedHashMap<String, Object>>) hits.iterator();
node2Map = it.next();
node1Map = it.next();
score2 = ( (Double) node2Map.get( "score" ) ).floatValue();
score1 = ( (Double) node1Map.get( "score" ) ).floatValue();
assertTrue(
"results returned in wrong order for score ordering",
( (String) node2Map.get( "self" ) ).endsWith( Long.toString( node2 ) ) );
assertTrue(
"results returned in wrong order for score ordering",
( (String) node1Map.get( "self" ) ).endsWith( Long.toString( node1 ) ) );
assertTrue( "scores are reversed", score2 > score1 );
}
/**
* POST ${org.neo4j.server.rest.web}/index/node/{indexName}/{key}/{value}
* "http://uri.for.node.to.index"
*/
@Test
public void shouldRespondWith201CreatedWhenIndexingJsonNodeUri()
{
final long nodeId = helper.createNode();
final String key = "key";
final String value = "value";
final String indexName = "testy";
helper.createNodeIndex( indexName );
JaxRsResponse response = RestRequest.req()
.post( functionalTestHelper.indexNodeUri( indexName ), createJsonStringFor( nodeId, key, value ) );
assertEquals( 201, response.getStatus() );
assertNotNull( response.getHeaders()
.getFirst( "Location" ) );
assertEquals( Arrays.asList( (Long) nodeId ), helper.getIndexedNodes( indexName, key, value ) );
}
@Test
public void shouldGetNodeRepresentationFromIndexUri() throws JsonParseException
{
long nodeId = helper.createNode();
String key = "key2";
String value = "value";
String indexName = "mindex";
helper.createNodeIndex( indexName );
JaxRsResponse response = RestRequest.req()
.post( functionalTestHelper.indexNodeUri( indexName ),
createJsonStringFor( nodeId, key, value ));
assertEquals( Status.CREATED.getStatusCode(), response.getStatus() );
String indexUri = response.getHeaders()
.getFirst( "Location" );
response = RestRequest.req()
.get( indexUri );
assertEquals( 200, response.getStatus() );
String entity = response.getEntity();
Map<String, Object> map = JsonHelper.jsonToMap( entity );
assertNotNull( map.get( "self" ) );
}
@Test
public void shouldGet404WhenRequestingIndexUriWhichDoesntExist()
{
String key = "key3";
String value = "value";
String indexName = "nosuchindex";
String indexUri = functionalTestHelper.nodeIndexUri() + indexName + "/" + key + "/" + value;
JaxRsResponse response = RestRequest.req()
.get( indexUri );
assertEquals( Status.NOT_FOUND.getStatusCode(), response.getStatus() );
}
@Test
public void shouldGet404WhenDeletingNonExtistentIndex()
{
String indexName = "nosuchindex";
String indexUri = functionalTestHelper.nodeIndexUri() + indexName;
JaxRsResponse response = RestRequest.req().delete(indexUri);
assertEquals( Status.NOT_FOUND.getStatusCode(), response.getStatus() );
}
@Test
public void shouldGet200AndArrayOfNodeRepsWhenGettingFromIndex() throws PropertyValueException
{
String key = "myKey";
String value = "myValue";
String name1 = "Thomas Anderson";
String name2 = "Agent Smith";
String indexName = "matrix";
final RestRequest request = RestRequest.req();
JaxRsResponse responseToPost = request.post( functionalTestHelper.nodeUri(), "{\"name\":\"" + name1 + "\"}" );
assertEquals( 201, responseToPost.getStatus() );
String location1 = responseToPost.getHeaders()
.getFirst( HttpHeaders.LOCATION );
responseToPost.close();
responseToPost = request.post( functionalTestHelper.nodeUri(), "{\"name\":\"" + name2 + "\"}" );
assertEquals( 201, responseToPost.getStatus() );
String location2 = responseToPost.getHeaders()
.getFirst( HttpHeaders.LOCATION );
responseToPost.close();
responseToPost = request.post( functionalTestHelper.indexNodeUri( indexName ),
createJsonStringFor( functionalTestHelper.getNodeIdFromUri( location1 ), key, value ) );
assertEquals( 201, responseToPost.getStatus() );
String indexLocation1 = responseToPost.getHeaders()
.getFirst( HttpHeaders.LOCATION );
responseToPost.close();
responseToPost = request.post( functionalTestHelper.indexNodeUri( indexName ),
createJsonStringFor( functionalTestHelper.getNodeIdFromUri( location2 ), key, value ) );
assertEquals( 201, responseToPost.getStatus() );
String indexLocation2 = responseToPost.getHeaders()
.getFirst( HttpHeaders.LOCATION );
Map<String, String> uriToName = new HashMap<>();
uriToName.put( indexLocation1, name1 );
uriToName.put( indexLocation2, name2 );
responseToPost.close();
JaxRsResponse response = RestRequest.req()
.get( functionalTestHelper.indexNodeUri( indexName, key, value ) );
assertEquals( 200, response.getStatus() );
Collection<?> items = (Collection<?>) JsonHelper.jsonToSingleValue( response.getEntity() );
int counter = 0;
for ( Object item : items )
{
Map<?, ?> map = (Map<?, ?>) item;
Map<?, ?> properties = (Map<?, ?>) map.get( "data" );
assertNotNull( map.get( "self" ) );
String indexedUri = (String) map.get( "indexed" );
assertEquals( uriToName.get( indexedUri ), properties.get( "name" ) );
counter++;
}
assertEquals( 2, counter );
response.close();
}
@Test
public void shouldGet200WhenGettingNodesFromIndexWithNoHits()
{
String indexName = "empty-index";
helper.createNodeIndex( indexName );
JaxRsResponse response = RestRequest.req()
.get( functionalTestHelper.indexNodeUri( indexName, "non-existent-key", "non-existent-value" ) );
assertEquals( 200, response.getStatus() );
response.close();
}
/**
* Delete node index.
*/
@Documented
@Test
public void shouldReturn204WhenRemovingNodeIndexes()
{
String indexName = "kvnode";
helper.createNodeIndex( indexName );
gen().noGraph()
.expectedStatus( 204 )
.delete( functionalTestHelper.indexNodeUri( indexName ) );
}
//
// REMOVING ENTRIES
//
/**
* Remove all entries with a given node from an index.
*/
@Documented
@Test
public void shouldBeAbleToRemoveIndexingById()
{
String key1 = "kvkey1";
String key2 = "kvkey2";
String value1 = "value1";
String value2 = "value2";
String indexName = "kvnode";
long node = helper.createNode( MapUtil.map( key1, value1, key1, value2, key2, value1, key2, value2 ) );
helper.addNodeToIndex( indexName, key1, value1, node );
helper.addNodeToIndex( indexName, key1, value2, node );
helper.addNodeToIndex( indexName, key2, value1, node );
helper.addNodeToIndex( indexName, key2, value2, node );
gen().noGraph()
.expectedStatus( 204 )
.delete( functionalTestHelper.indexNodeUri( indexName ) + "/" + node );
assertEquals( 0, helper.getIndexedNodes( indexName, key1, value1 )
.size() );
assertEquals( 0, helper.getIndexedNodes( indexName, key1, value2 )
.size() );
assertEquals( 0, helper.getIndexedNodes( indexName, key2, value1 )
.size() );
assertEquals( 0, helper.getIndexedNodes( indexName, key2, value2 )
.size() );
}
/**
* Remove all entries with a given node and key from an index.
*/
@Documented
@Test
public void shouldBeAbleToRemoveIndexingByIdAndKey()
{
String key1 = "kvkey1";
String key2 = "kvkey2";
String value1 = "value1";
String value2 = "value2";
String indexName = "kvnode";
long node = helper.createNode( MapUtil.map( key1, value1, key1, value2, key2, value1, key2, value2 ) );
helper.addNodeToIndex( indexName, key1, value1, node );
helper.addNodeToIndex( indexName, key1, value2, node );
helper.addNodeToIndex( indexName, key2, value1, node );
helper.addNodeToIndex( indexName, key2, value2, node );
gen().noGraph()
.expectedStatus( 204 )
.delete( functionalTestHelper.nodeIndexUri() + indexName + "/" + key2 + "/" + node );
assertEquals( 1, helper.getIndexedNodes( indexName, key1, value1 )
.size() );
assertEquals( 1, helper.getIndexedNodes( indexName, key1, value2 )
.size() );
assertEquals( 0, helper.getIndexedNodes( indexName, key2, value1 )
.size() );
assertEquals( 0, helper.getIndexedNodes( indexName, key2, value2 )
.size() );
}
/**
* Remove all entries with a given node, key and value from an index.
*/
@Documented
@Test
public void shouldBeAbleToRemoveIndexingByIdAndKeyAndValue()
{
String key1 = "kvkey1";
String key2 = "kvkey2";
String value1 = "value1";
String value2 = "value2";
String indexName = "kvnode";
long node = helper.createNode( MapUtil.map( key1, value1, key1, value2, key2, value1, key2, value2 ) );
helper.addNodeToIndex( indexName, key1, value1, node );
helper.addNodeToIndex( indexName, key1, value2, node );
helper.addNodeToIndex( indexName, key2, value1, node );
helper.addNodeToIndex( indexName, key2, value2, node );
gen().noGraph()
.expectedStatus( 204 )
.delete( functionalTestHelper.nodeIndexUri() + indexName + "/" + key1 + "/" + value1 + "/" + node );
assertEquals( 0, helper.getIndexedNodes( indexName, key1, value1 )
.size() );
assertEquals( 1, helper.getIndexedNodes( indexName, key1, value2 )
.size() );
assertEquals( 1, helper.getIndexedNodes( indexName, key2, value1 )
.size() );
assertEquals( 1, helper.getIndexedNodes( indexName, key2, value2 )
.size() );
}
@Test
public void shouldBeAbleToIndexValuesContainingSpaces() throws Exception
{
final long nodeId = helper.createNode();
final String key = "key";
final String value = "value with spaces in it";
String indexName = "spacey-values";
helper.createNodeIndex( indexName );
final RestRequest request = RestRequest.req();
JaxRsResponse response = request.post( functionalTestHelper.indexNodeUri( indexName ),
createJsonStringFor( nodeId, key, value ) );
assertEquals( Status.CREATED.getStatusCode(), response.getStatus() );
URI location = response.getLocation();
response.close();
response = request.get( functionalTestHelper.indexNodeUri( indexName, key, URIHelper.encode( value ) ) );
assertEquals( Status.OK.getStatusCode(), response.getStatus() );
Collection<?> hits = (Collection<?>) JsonHelper.jsonToSingleValue( response.getEntity() );
assertEquals( 1, hits.size() );
response.close();
CLIENT.resource( location )
.delete();
response = request.get( functionalTestHelper.indexNodeUri( indexName, key, URIHelper.encode( value ) ) );
hits = (Collection<?>) JsonHelper.jsonToSingleValue( response.getEntity() );
assertEquals( 0, hits.size() );
}
private String createJsonStringFor( final long nodeId, final String key, final String value )
{
return "{\"key\": \"" + key + "\", \"value\": \"" + value + "\", \"uri\": \""
+ functionalTestHelper.nodeUri( nodeId ) + "\"}";
}
@Test
public void shouldRespondWith400WhenSendingCorruptJson() throws Exception
{
final String indexName = "botherable-index";
helper.createNodeIndex( indexName );
final String corruptJson = "{\"key\" \"myKey\"}";
JaxRsResponse response = RestRequest.req()
.post( functionalTestHelper.indexNodeUri( indexName ),
corruptJson );
assertEquals( 400, response.getStatus() );
response.close();
}
/**
* Get or create unique node (create).
*
* The node is created if it doesn't exist in the unique index already.
*/
@Documented
@Test
public void get_or_create_a_node_in_an_unique_index() throws Exception
{
final String index = "people", key = "name", value = "Tobias";
helper.createNodeIndex( index );
ResponseEntity response = gen().noGraph()
.expectedStatus( 201 /* created */)
.payloadType( MediaType.APPLICATION_JSON_TYPE )
.payload( "{\"key\": \"" + key + "\", \"value\": \"" + value
+ "\", \"properties\": {\"" + key + "\": \"" + value
+ "\", \"sequence\": 1}}" )
.post( functionalTestHelper.nodeIndexUri() + index + "?uniqueness=get_or_create" );
MultivaluedMap<String, String> headers = response.response().getHeaders();
Map<String, Object> result = JsonHelper.jsonToMap( response.entity() );
assertEquals( result.get( "indexed" ), headers.getFirst( "Location" ) );
Map<String, Object> data = assertCast( Map.class, result.get( "data" ) );
assertEquals( value, data.get( key ) );
assertEquals( 1, data.get( "sequence" ) );
}
@Test
public void get_or_create_node_with_array_properties() throws Exception
{
final String index = "people", key = "name", value = "Tobias";
helper.createNodeIndex( index );
ResponseEntity response = gen()
.expectedStatus( 201 /* created */)
.payloadType( MediaType.APPLICATION_JSON_TYPE )
.payload( "{\"key\": \"" + key + "\", \"value\": \"" + value
+ "\", \"properties\": {\"" + key + "\": \"" + value
+ "\", \"array\": [1,2,3]}}" )
.post( functionalTestHelper.nodeIndexUri() + index + "?unique" );
MultivaluedMap<String, String> headers = response.response().getHeaders();
Map<String, Object> result = JsonHelper.jsonToMap( response.entity() );
String location = headers.getFirst("Location");
assertEquals( result.get( "indexed" ), location);
Map<String, Object> data = assertCast( Map.class, result.get( "data" ) );
assertEquals( value, data.get( key ) );
assertEquals(Arrays.asList( 1, 2, 3), data.get( "array" ) );
Node node;
try ( Transaction tx = graphdb().beginTx() )
{
node = graphdb().index().forNodes(index).get(key, value).getSingle();
}
assertThat(node, inTx( graphdb(), hasProperty( key ).withValue( value ) ));
assertThat(node, inTx( graphdb(), hasProperty( "array" ).withValue( new int[]{1, 2, 3} ) ));
}
/**
* Get or create unique node (existing).
*
* Here,
* a node is not created but the existing unique node returned, since another node
* is indexed with the same data already. The node data returned is then that of the
* already existing node.
*/
@Documented
@Test
public void get_or_create_unique_node_if_already_existing() throws Exception
{
final String index = "people", key = "name", value = "Peter";
GraphDatabaseService graphdb = graphdb();
try ( Transaction tx = graphdb().beginTx() )
{
Node peter = graphdb.createNode();
peter.setProperty( key, value );
peter.setProperty( "sequence", 1 );
graphdb.index().forNodes( index ).add( peter, key, value );
tx.success();
}
helper.createNodeIndex( index );
ResponseEntity response = gen().noGraph()
.expectedStatus( 200 /* ok */)
.payloadType( MediaType.APPLICATION_JSON_TYPE )
.payload( "{\"key\": \"" + key + "\", \"value\": \"" + value
+ "\", \"properties\": {\"" + key + "\": \"" + value
+ "\", \"sequence\": 2}}" )
.post( functionalTestHelper.nodeIndexUri() + index + "?uniqueness=get_or_create" );
Map<String, Object> result = JsonHelper.jsonToMap( response.entity() );
Map<String, Object> data = assertCast( Map.class, result.get( "data" ) );
assertEquals( value, data.get( key ) );
assertEquals( 1, data.get( "sequence" ) );
}
/**
* Create a unique node or return fail (create).
*
* Here, in case
* of an already existing node, an error should be returned. In this
* example, no existing indexed node is found and a new node is created.
*/
@Documented
@Test
public void create_a_unique_node_or_fail_create() throws Exception
{
final String index = "people", key = "name", value = "Tobias";
helper.createNodeIndex( index );
ResponseEntity response = gen.get().noGraph()
.expectedStatus( 201 /* created */)
.payloadType( MediaType.APPLICATION_JSON_TYPE )
.payload( "{\"key\": \"" + key + "\", \"value\": \"" + value
+ "\", \"properties\": {\"" + key + "\": \"" + value
+ "\", \"sequence\": 1}}" )
.post( functionalTestHelper.nodeIndexUri() + index + "?uniqueness=create_or_fail" );
MultivaluedMap<String, String> headers = response.response().getHeaders();
Map<String, Object> result = JsonHelper.jsonToMap( response.entity() );
assertEquals( result.get( "indexed" ), headers.getFirst( "Location" ) );
Map<String, Object> data = assertCast( Map.class, result.get( "data" ) );
assertEquals( value, data.get( key ) );
assertEquals( 1, data.get( "sequence" ) );
}
/**
* Create a unique node or return fail (fail).
*
* Here, in case
* of an already existing node, an error should be returned. In this
* example, an existing node indexed with the same data
* is found and an error is returned.
*/
@Documented
@Test
public void create_a_unique_node_or_return_fail___fail() throws Exception
{
final String index = "people", key = "name", value = "Peter";
GraphDatabaseService graphdb = graphdb();
helper.createNodeIndex( index );
try ( Transaction tx = graphdb.beginTx() )
{
Node peter = graphdb.createNode();
peter.setProperty( key, value );
peter.setProperty( "sequence", 1 );
graphdb.index().forNodes( index ).add( peter, key, value );
tx.success();
}
RestRequest.req();
ResponseEntity response = gen.get().noGraph()
.expectedStatus( 409 /* conflict */)
.payloadType( MediaType.APPLICATION_JSON_TYPE )
.payload( "{\"key\": \"" + key + "\", \"value\": \"" + value
+ "\", \"properties\": {\"" + key + "\": \"" + value
+ "\", \"sequence\": 2}}" )
.post( functionalTestHelper.nodeIndexUri() + index + "?uniqueness=create_or_fail" );
Map<String, Object> result = JsonHelper.jsonToMap( response.entity() );
Map<String, Object> data = assertCast( Map.class, result.get( "data" ) );
assertEquals( value, data.get( key ) );
assertEquals( 1, data.get( "sequence" ) );
}
/**
* Add an existing node to unique index (not indexed).
*
* Associates a node with the given key/value pair in the given unique
* index.
*
* In this example, we are using `create_or_fail` uniqueness.
*/
@Documented
@Test
public void addExistingNodeToUniqueIndexAdded() throws Exception
{
final String indexName = "favorites";
final String key = "some-key";
final String value = "some value";
long nodeId = createNode();
// implicitly create the index
gen().noGraph()
.expectedStatus( 201 /* created */ )
.payload(
JsonHelper.createJsonFrom( generateNodeIndexCreationPayload( key, value,
functionalTestHelper.nodeUri( nodeId ) ) ) )
.post( functionalTestHelper.indexNodeUri( indexName ) + "?uniqueness=create_or_fail" );
// look if we get one entry back
JaxRsResponse response = RestRequest.req()
.get( functionalTestHelper.indexNodeUri( indexName, key, URIHelper.encode( value ) ) );
String entity = response.getEntity();
Collection<?> hits = (Collection<?>) JsonHelper.jsonToSingleValue( entity );
assertEquals( 1, hits.size() );
}
/**
* Add an existing node to unique index (already indexed).
*
* In this case, the node already exists in the index, and thus we get a `HTTP 409` status response,
* as we have set the uniqueness to `create_or_fail`.
*
*/
@Documented
@Test
public void addExistingNodeToUniqueIndexExisting() throws Exception
{
final String indexName = "favorites";
final String key = "some-key";
final String value = "some value";
try ( Transaction tx = graphdb().beginTx() )
{
Node peter = graphdb().createNode();
peter.setProperty( key, value );
graphdb().index().forNodes( indexName ).add( peter, key, value );
tx.success();
}
gen().noGraph()
.expectedStatus( 409 /* conflict */ )
.payload(
JsonHelper.createJsonFrom( generateNodeIndexCreationPayload( key, value,
functionalTestHelper.nodeUri( createNode() ) ) ) )
.post( functionalTestHelper.indexNodeUri( indexName ) + "?uniqueness=create_or_fail" );
}
/**
* Backward Compatibility Test (using old syntax ?unique)
* Put node if absent - Create.
*
* Add a node to an index unless a node already exists for the given index data. In
* this case, a new node is created since nothing existing is found in the index.
*/
@Documented
@Test
public void put_node_if_absent___create() throws Exception
{
final String index = "people", key = "name", value = "Mattias";
helper.createNodeIndex( index );
String uri = functionalTestHelper.nodeIndexUri() + index + "?unique";
gen().expectedStatus( 201 /* created */ )
.payloadType( MediaType.APPLICATION_JSON_TYPE )
.payload( "{\"key\": \"" + key + "\", \"value\": \"" + value + "\", \"uri\":\"" + functionalTestHelper.nodeUri( helper.createNode() ) + "\"}" )
.post( uri );
}
@Test
public void already_indexed_node_should_not_fail_on_create_or_fail() throws Exception
{
// Given
final String index = "nodeIndex", key = "name", value = "Peter";
GraphDatabaseService graphdb = graphdb();
helper.createNodeIndex( index );
Node node;
try ( Transaction tx = graphdb.beginTx() )
{
node = graphdb.createNode();
graphdb.index().forNodes( index ).add( node, key, value );
tx.success();
}
// When & Then
gen.get()
.noGraph()
.expectedStatus( 201 )
.payloadType( MediaType.APPLICATION_JSON_TYPE )
.payload(
"{\"key\": \"" + key + "\", \"value\": \"" + value + "\", \"uri\":\""
+ functionalTestHelper.nodeUri( node.getId() ) + "\"}" )
.post( functionalTestHelper.nodeIndexUri() + index + "?uniqueness=create_or_fail" );
}
private static <T> T assertCast( Class<T> type, Object object )
{
assertTrue( type.isInstance( object ) );
return type.cast( object );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_IndexNodeDocIT.java
|
2,355
|
public class HtmlDocIT extends AbstractRestFunctionalTestBase
{
private long thomasAnderson;
private long trinity;
private long thomasAndersonLovesTrinity;
private static FunctionalTestHelper functionalTestHelper;
private static GraphDbHelper helper;
@BeforeClass
public static void setupServer() throws IOException
{
functionalTestHelper = new FunctionalTestHelper( server() );
helper = functionalTestHelper.getGraphDbHelper();
}
@Before
public void setupTheDatabase()
{
cleanDatabase();
createTheMatrix();
}
private void createTheMatrix()
{
// Create the matrix example
thomasAnderson = createAndIndexNode( "Thomas Anderson" );
trinity = createAndIndexNode( "Trinity" );
long tank = createAndIndexNode( "Tank" );
long knowsRelationshipId = helper.createRelationship( "KNOWS", thomasAnderson, trinity );
thomasAndersonLovesTrinity = helper.createRelationship( "LOVES", thomasAnderson, trinity );
helper.setRelationshipProperties( thomasAndersonLovesTrinity,
Collections.singletonMap( "strength", (Object) 100 ) );
helper.createRelationship( "KNOWS", thomasAnderson, tank );
helper.createRelationship( "KNOWS", trinity, tank );
// index a relationship
helper.createRelationshipIndex( "relationships" );
helper.addRelationshipToIndex( "relationships", "key", "value", knowsRelationshipId );
// index a relationship
helper.createRelationshipIndex( "relationships2" );
helper.addRelationshipToIndex( "relationships2", "key2", "value2", knowsRelationshipId );
}
private long createAndIndexNode( String name )
{
long id = helper.createNode();
helper.setNodeProperties( id, Collections.singletonMap( "name", (Object) name ) );
helper.addNodeToIndex( "node", "name", name, id );
return id;
}
@Test
public void shouldGetRoot() {
JaxRsResponse response = RestRequest.req().get(functionalTestHelper.dataUri(), MediaType.TEXT_HTML_TYPE);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
assertValidHtml( response.getEntity() );
response.close();
}
@Test
public void shouldGetNodeIndexRoot() {
JaxRsResponse response = RestRequest.req().get(functionalTestHelper.nodeIndexUri(), MediaType.TEXT_HTML_TYPE);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
assertValidHtml( response.getEntity() );
response.close();
}
@Test
public void shouldGetRelationshipIndexRoot() {
JaxRsResponse response = RestRequest.req().get(functionalTestHelper.relationshipIndexUri(), MediaType.TEXT_HTML_TYPE);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
assertValidHtml( response.getEntity() );
response.close();
}
@Test
public void shouldGetTrinityWhenSearchingForHer() {
JaxRsResponse response = RestRequest.req().get(functionalTestHelper.indexNodeUri("node", "name", "Trinity"), MediaType.TEXT_HTML_TYPE);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.getEntity();
assertTrue(entity.contains("Trinity"));
assertValidHtml(entity);
response.close();
}
@Test
public void shouldGetThomasAndersonDirectly() {
JaxRsResponse response = RestRequest.req().get(functionalTestHelper.nodeUri(thomasAnderson), MediaType.TEXT_HTML_TYPE);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.getEntity();
assertTrue(entity.contains("Thomas Anderson"));
assertValidHtml(entity);
response.close();
}
@Test
public void shouldGetSomeRelationships() {
final RestRequest request = RestRequest.req();
JaxRsResponse response = request.get(functionalTestHelper.relationshipsUri(thomasAnderson, RelationshipDirection.all.name(), "KNOWS"), MediaType.TEXT_HTML_TYPE);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.getEntity();
assertTrue(entity.contains("KNOWS"));
assertFalse(entity.contains("LOVES"));
assertValidHtml(entity);
response.close();
response = request.get(functionalTestHelper.relationshipsUri(thomasAnderson, RelationshipDirection.all.name(), "LOVES"),
MediaType.TEXT_HTML_TYPE);
entity = response.getEntity();
assertFalse(entity.contains("KNOWS"));
assertTrue(entity.contains("LOVES"));
assertValidHtml(entity);
response.close();
response = request.get(
functionalTestHelper.relationshipsUri(thomasAnderson, RelationshipDirection.all.name(), "LOVES",
"KNOWS"),MediaType.TEXT_HTML_TYPE);
entity = response.getEntity();
assertTrue(entity.contains("KNOWS"));
assertTrue(entity.contains("LOVES"));
assertValidHtml(entity);
response.close();
}
@Test
public void shouldGetThomasAndersonLovesTrinityRelationship() {
JaxRsResponse response = RestRequest.req().get(functionalTestHelper.relationshipUri(thomasAndersonLovesTrinity), MediaType.TEXT_HTML_TYPE);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.getEntity();
assertTrue(entity.contains("strength"));
assertTrue(entity.contains("100"));
assertTrue(entity.contains("LOVES"));
assertValidHtml(entity);
response.close();
}
private void assertValidHtml( String entity )
{
assertTrue( entity.contains( "<html>" ) );
assertTrue( entity.contains( "</html>" ) );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_HtmlDocIT.java
|
2,356
|
public class GetRelationshipPropertiesDocIT extends AbstractRestFunctionalTestBase
{
private static String baseRelationshipUri;
private static FunctionalTestHelper functionalTestHelper;
private static GraphDbHelper helper;
@BeforeClass
public static void setupServer() throws IOException
{
functionalTestHelper = new FunctionalTestHelper( server() );
helper = functionalTestHelper.getGraphDbHelper();
}
@Before
public void setupTheDatabase()
{
cleanDatabase();
long relationship = helper.createRelationship( "LIKES" );
Map<String, Object> map = new HashMap<String, Object>();
map.put( "foo", "bar" );
helper.setRelationshipProperties( relationship, map );
baseRelationshipUri = functionalTestHelper.dataUri() + "relationship/" + relationship + "/properties/";
}
@Test
public void shouldGet204ForNoProperties()
{
long relId = helper.createRelationship( "LIKES" );
JaxRsResponse response = RestRequest.req().get( functionalTestHelper.dataUri() + "relationship/" + relId
+ "/properties" );
assertEquals( 204, response.getStatus() );
response.close();
}
@Test
public void shouldGet200AndContentLengthForProperties()
{
long relId = helper.createRelationship( "LIKES" );
helper.setRelationshipProperties( relId, Collections.<String, Object>singletonMap( "foo", "bar" ) );
JaxRsResponse response = RestRequest.req().get( functionalTestHelper.dataUri() + "relationship/" + relId
+ "/properties" );
assertEquals( 200, response.getStatus() );
assertNotNull( response.getHeaders()
.get( "Content-Length" ) );
response.close();
}
@Test
public void shouldGet404ForPropertiesOnNonExistentRelationship()
{
JaxRsResponse response = RestRequest.req().get( functionalTestHelper.dataUri() +
"relationship/999999/properties" );
assertEquals( 404, response.getStatus() );
response.close();
}
@Test
public void shouldBeJSONContentTypeOnPropertiesResponse()
{
long relId = helper.createRelationship( "LIKES" );
helper.setRelationshipProperties( relId, Collections.<String, Object>singletonMap( "foo", "bar" ) );
JaxRsResponse response = RestRequest.req().get( functionalTestHelper.dataUri() + "relationship/" + relId
+ "/properties" );
assertThat( response.getType().toString(), containsString( MediaType.APPLICATION_JSON ) );
response.close();
}
private String getPropertyUri( String key )
{
return baseRelationshipUri + key;
}
@Test
public void shouldGet404ForNoProperty()
{
JaxRsResponse response = RestRequest.req().get( getPropertyUri( "baz" ) );
assertEquals( 404, response.getStatus() );
response.close();
}
@Test
public void shouldGet404ForNonExistingRelationship()
{
String uri = functionalTestHelper.dataUri() + "relationship/999999/properties/foo";
JaxRsResponse response = RestRequest.req().get( uri );
assertEquals( 404, response.getStatus() );
response.close();
}
@Test
public void shouldBeValidJSONOnResponse() throws JsonParseException
{
JaxRsResponse response = RestRequest.req().get( getPropertyUri( "foo" ) );
assertThat( response.getType().toString(), containsString( MediaType.APPLICATION_JSON ) );
assertNotNull( JsonHelper.createJsonFrom( response.getEntity() ) );
response.close();
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_GetRelationshipPropertiesDocIT.java
|
2,357
|
public class GetOnRootDocIT extends AbstractRestFunctionalTestBase
{
/**
* The service root is your starting point to discover the REST API. It
* contains the basic starting points for the database, and some version and
* extension information.
*/
@Documented
@Test
@Graph("I know you")
@Title("Get service root")
public void assert200OkFromGet() throws Exception
{
String body = gen.get().expectedStatus( 200 ).get( getDataUri() ).entity();
Map<String, Object> map = JsonHelper.jsonToMap( body );
assertEquals( getDataUri() + "node", map.get( "node" ) );
assertNotNull( map.get( "node_index" ) );
assertNotNull( map.get( "relationship_index" ) );
assertNotNull( map.get( "extensions_info" ) );
assertNotNull( map.get( "batch" ) );
assertNotNull( map.get( "cypher" ) );
assertNotNull( map.get( "indexes" ) );
assertNotNull( map.get( "constraints" ) );
assertNotNull( map.get( "node_labels" ) );
assertEquals( Version.getKernel().getReleaseVersion(), map.get( "neo4j_version" ) );
// Make sure advertised urls work
JaxRsResponse response;
if ( map.get( "reference_node" ) != null )
{
response = RestRequest.req().get(
(String) map.get( "reference_node" ) );
assertEquals( 200, response.getStatus() );
response.close();
}
response = RestRequest.req().get( (String) map.get( "node_index" ) );
assertTrue( response.getStatus() == 200 || response.getStatus() == 204 );
response.close();
response = RestRequest.req().get(
(String) map.get( "relationship_index" ) );
assertTrue( response.getStatus() == 200 || response.getStatus() == 204 );
response.close();
response = RestRequest.req().get( (String) map.get( "extensions_info" ) );
assertEquals( 200, response.getStatus() );
response.close();
response = RestRequest.req().post( (String) map.get( "batch" ), "[]" );
assertEquals( 200, response.getStatus() );
response.close();
response = RestRequest.req().post( (String) map.get( "cypher" ), "{\"query\":\"CREATE (n) RETURN n\"}" );
assertEquals( 200, response.getStatus() );
response.close();
response = RestRequest.req().get( (String) map.get( "indexes" ) );
assertEquals( 200, response.getStatus() );
response.close();
response = RestRequest.req().get( (String) map.get( "constraints" ) );
assertEquals( 200, response.getStatus() );
response.close();
response = RestRequest.req().get( (String) map.get( "node_labels" ) );
assertEquals( 200, response.getStatus() );
response.close();
}
/**
* All responses from the REST API can be transmitted as JSON streams, resulting in
* better performance and lower memory overhead on the server side. To use
* streaming, supply the header `X-Stream: true` with each request.
*/
@Documented
@Test
public void streaming() throws Exception
{
data.get();
ResponseEntity responseEntity = gen().docHeadingLevel( 2 )
.withHeader( StreamingFormat.STREAM_HEADER, "true" )
.expectedType( APPLICATION_JSON_TYPE )
.expectedStatus( 200 )
.get( getDataUri() );
JaxRsResponse response = responseEntity.response();
// this gets the full media type, including things like
// ; stream=true at the end
String foundMediaType = response.getType()
.toString();
String expectedMediaType = StreamingFormat.MEDIA_TYPE.toString();
assertEquals( expectedMediaType, foundMediaType );
String body = responseEntity.entity();
Map<String, Object> map = JsonHelper.jsonToMap( body );
assertEquals( getDataUri() + "node", map.get( "node" ) );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_GetOnRootDocIT.java
|
2,358
|
public class GetNodePropertiesDocIT extends AbstractRestFunctionalTestBase
{
private static FunctionalTestHelper functionalTestHelper;
private RestRequest req;
@BeforeClass
public static void setupServer() throws IOException
{
functionalTestHelper = new FunctionalTestHelper( server() );
}
@Before
public void cleanTheDatabase()
{
cleanDatabase();
req = RestRequest.req();
}
/**
* Get properties for node (empty result).
*
* If there are no properties, there will be an HTTP 204 response.
*/
@Documented
@Test
public void shouldGet204ForNoProperties() {
JaxRsResponse createResponse = req.post(functionalTestHelper.dataUri() + "node/", "");
gen.get()
.expectedStatus(204)
.get(createResponse.getLocation()
.toString() + "/properties");
}
/**
* Get properties for node.
*/
@Documented
@Test
public void shouldGet200ForProperties() throws JsonParseException {
String entity = JsonHelper.createJsonFrom(Collections.singletonMap("foo", "bar"));
JaxRsResponse createResponse = req.post(functionalTestHelper.dataUri() + "node/", entity);
gen.get()
.expectedStatus(200)
.get(createResponse.getLocation()
.toString() + "/properties");
}
@Test
public void shouldGetContentLengthHeaderForRetrievingProperties() throws JsonParseException
{
String entity = JsonHelper.createJsonFrom(Collections.singletonMap("foo", "bar"));
final RestRequest request = req;
JaxRsResponse createResponse = request.post(functionalTestHelper.dataUri() + "node/", entity);
JaxRsResponse response = request.get(createResponse.getLocation().toString() + "/properties");
assertNotNull( response.getHeaders().get("Content-Length") );
}
@Test
public void shouldGetCorrectContentEncodingRetrievingProperties() throws PropertyValueException
{
String asianText = "\u4f8b\u5b50";
String germanText = "öäüÖÄÜß";
String complicatedString = asianText + germanText;
String entity = JsonHelper.createJsonFrom( Collections.singletonMap( "foo", complicatedString ));
final RestRequest request = req;
JaxRsResponse createResponse = request.post(functionalTestHelper.dataUri() + "node/", entity);
String response = (String) JsonHelper.jsonToSingleValue( request.get( getPropertyUri( createResponse.getLocation().toString(), "foo" ) ).getEntity() );
assertEquals( complicatedString, response );
}
@Test
public void shouldGetCorrectContentEncodingRetrievingPropertiesWithStreaming() throws PropertyValueException
{
String asianText = "\u4f8b\u5b50";
String germanText = "öäüÖÄÜß";
String complicatedString = asianText + germanText;
String entity = JsonHelper.createJsonFrom( Collections.singletonMap( "foo", complicatedString ) );
final RestRequest request = req.header( StreamingJsonFormat.STREAM_HEADER,"true");
JaxRsResponse createResponse = request.post(functionalTestHelper.dataUri() + "node/", entity);
String response = (String) JsonHelper.jsonToSingleValue( request.get( getPropertyUri( createResponse.getLocation().toString(), "foo" ) , new MediaType( "application","json", stringMap( "stream", "true" ) )).getEntity() );
assertEquals( complicatedString, response );
}
@Test
public void shouldGet404ForPropertiesOnNonExistentNode() {
JaxRsResponse response = RestRequest.req().get(functionalTestHelper.dataUri() + "node/999999/properties");
assertEquals(404, response.getStatus());
}
@Test
public void shouldBeJSONContentTypeOnPropertiesResponse() throws JsonParseException
{
String entity = JsonHelper.createJsonFrom(Collections.singletonMap("foo", "bar"));
JaxRsResponse createResource = req.post(functionalTestHelper.dataUri() + "node/", entity);
JaxRsResponse response = req.get(createResource.getLocation().toString() + "/properties");
assertThat( response.getType().toString(), containsString( MediaType.APPLICATION_JSON ) );
}
@Test
public void shouldGet404ForNoProperty()
{
final JaxRsResponse createResponse = req.post(functionalTestHelper.dataUri() + "node/", "");
JaxRsResponse response = req.get(getPropertyUri(createResponse.getLocation().toString(), "foo"));
assertEquals(404, response.getStatus());
}
/**
* Get property for node.
*
* Get a single node property from a node.
*/
@Documented
@Test
public void shouldGet200ForProperty() throws JsonParseException
{
String entity = JsonHelper.createJsonFrom(Collections.singletonMap("foo", "bar"));
JaxRsResponse createResponse = req.post(functionalTestHelper.dataUri() + "node/", entity);
JaxRsResponse response = req.get(getPropertyUri(createResponse.getLocation().toString(), "foo"));
assertEquals(200, response.getStatus());
gen.get()
.expectedStatus( 200 )
.get(getPropertyUri(createResponse.getLocation()
.toString(), "foo"));
}
@Test
public void shouldGet404ForPropertyOnNonExistentNode() {
JaxRsResponse response = RestRequest.req().get(getPropertyUri(functionalTestHelper.dataUri() + "node/" + "999999", "foo"));
assertEquals(404, response.getStatus());
}
@Test
public void shouldBeJSONContentTypeOnPropertyResponse() throws JsonParseException {
String entity = JsonHelper.createJsonFrom( Collections.singletonMap( "foo", "bar" ) );
JaxRsResponse createResponse = req.post(functionalTestHelper.dataUri() + "node/", entity);
JaxRsResponse response = req.get(getPropertyUri(createResponse.getLocation().toString(), "foo"));
assertThat( response.getType().toString(), containsString(MediaType.APPLICATION_JSON) );
createResponse.close();
response.close();
}
private String getPropertyUri( final String baseUri, final String key )
{
return baseUri + "/properties/" + key;
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_GetNodePropertiesDocIT.java
|
2,359
|
public class GetIndexRootDocIT extends AbstractRestFunctionalTestBase
{
private static FunctionalTestHelper functionalTestHelper;
@BeforeClass
public static void setupServer() throws IOException
{
functionalTestHelper = new FunctionalTestHelper( server() );
}
@Before
public void cleanTheDatabase()
{
cleanDatabase();
}
/**
* /db/data/index is not itself a resource
*
*/
@Test
public void shouldRespondWith404ForNonResourceIndexPath() throws Exception
{
JaxRsResponse response = RestRequest.req().get(functionalTestHelper.indexUri());
assertEquals( 404, response.getStatus() );
response.close();
}
/**
* /db/data/index/node should be a resource with no content
*
* @throws Exception
*/
@Test
public void shouldRespondWithNodeIndexes() throws Exception {
JaxRsResponse response = RestRequest.req().get(functionalTestHelper.nodeIndexUri());
assertResponseContainsNoIndexesOtherThanAutoIndexes(response);
response.close();
}
private void assertResponseContainsNoIndexesOtherThanAutoIndexes( JaxRsResponse response ) throws JsonParseException
{
switch ( response.getStatus() )
{
case 204: return; // OK no auto indices
case 200: assertEquals( 0, functionalTestHelper.removeAnyAutoIndex( jsonToMap( response.getEntity() ) ).size() ); break;
default: fail( "Invalid response code " + response.getStatus() );
}
}
/**
* /db/data/index/relationship should be a resource with no content
*
* @throws Exception
*/
@Test
public void shouldRespondWithRelationshipIndexes() throws Exception {
JaxRsResponse response = RestRequest.req().get(functionalTestHelper.relationshipIndexUri());
assertResponseContainsNoIndexesOtherThanAutoIndexes(response);
response.close();
}
// TODO More tests...
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_GetIndexRootDocIT.java
|
2,360
|
class DocumentationData
{
private String payload;
private MediaType payloadType = MediaType.APPLICATION_JSON_TYPE;
public String title;
public String description;
public String uri;
public String method;
public int status;
public String entity;
public Map<String, String> requestHeaders;
public Map<String, String> responseHeaders;
public boolean ignore;
public void setPayload( final String payload )
{
this.payload = payload;
}
public String getPayload()
{
if ( this.payload != null && !this.payload.trim()
.isEmpty()
&& MediaType.APPLICATION_JSON_TYPE.equals( payloadType ) )
{
return JSONPrettifier.parse( this.payload );
}
else
{
return this.payload;
}
}
public String getPrettifiedEntity()
{
return JSONPrettifier.parse( entity );
}
public void setPayloadType( final MediaType payloadType )
{
this.payloadType = payloadType;
}
public void setDescription( final String description )
{
this.description = description;
}
public void setTitle( final String title )
{
this.title = title;
}
public void setUri( final String uri )
{
this.uri = uri;
}
public void setMethod( final String method )
{
this.method = method;
}
public void setStatus( final int responseCode )
{
this.status = responseCode;
}
public void setEntity( final String entity )
{
this.entity = entity;
}
public void setResponseHeaders( final Map<String, String> response )
{
responseHeaders = response;
}
public void setRequestHeaders( final Map<String, String> request )
{
requestHeaders = request;
}
public void setIgnore() {
this.ignore = true;
}
@Override
public String toString()
{
return "DocumentationData [payload=" + payload + ", title=" + title + ", description=" + description
+ ", uri=" + uri + ", method=" + method + ", status=" + status + ", entity=" + entity
+ ", requestHeaders=" + requestHeaders + ", responseHeaders=" + responseHeaders + "]";
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_DocumentationData.java
|
2,361
|
public class DiscoveryServiceDocIT extends AbstractRestFunctionalTestBase
{
@Before
public void cleanTheDatabase()
{
cleanDatabase();
}
@Test
public void shouldRespondWith200WhenRetrievingDiscoveryDocument() throws Exception
{
JaxRsResponse response = getDiscoveryDocument();
assertEquals( 200, response.getStatus() );
response.close();
}
@Test
public void shouldGetContentLengthHeaderWhenRetrievingDiscoveryDocument() throws Exception
{
JaxRsResponse response = getDiscoveryDocument();
assertNotNull( response.getHeaders()
.get( "Content-Length" ) );
response.close();
}
@Test
public void shouldHaveJsonMediaTypeWhenRetrievingDiscoveryDocument() throws Exception
{
JaxRsResponse response = getDiscoveryDocument();
assertThat( response.getType().toString(), containsString(MediaType.APPLICATION_JSON) );
response.close();
}
@Test
public void shouldHaveJsonDataInResponse() throws Exception
{
JaxRsResponse response = getDiscoveryDocument();
Map<String, Object> map = JsonHelper.jsonToMap( response.getEntity() );
String managementKey = "management";
assertTrue( map.containsKey( managementKey ) );
assertNotNull( map.get( managementKey ) );
String dataKey = "data";
assertTrue( map.containsKey( dataKey ) );
assertNotNull( map.get( dataKey ) );
response.close();
}
@Test
public void shouldRedirectToWebadminOnHtmlRequest() throws Exception
{
Client nonRedirectingClient = Client.create();
nonRedirectingClient.setFollowRedirects( false );
JaxRsResponse clientResponse = new RestRequest(null,nonRedirectingClient).get(server().baseUri().toString(),MediaType.TEXT_HTML_TYPE);
assertEquals( 303, clientResponse.getStatus() );
}
private JaxRsResponse getDiscoveryDocument() throws Exception
{
return new RestRequest(server().baseUri()).get();
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_DiscoveryServiceDocIT.java
|
2,362
|
public class DisableWADLDocIT extends AbstractRestFunctionalTestBase
{
private static FunctionalTestHelper functionalTestHelper;
private static GraphDbHelper helper;
@BeforeClass
public static void setupServer() throws IOException
{
functionalTestHelper = new FunctionalTestHelper( server() );
helper = functionalTestHelper.getGraphDbHelper();
}
@Before
public void setupTheDatabase()
{
cleanDatabase();
}
@Test
public void should404OnAnyUriEndinginWADL() throws Exception
{
URI nodeUri = new URI( "http://localhost:7474/db/data/application.wadl" );
HttpClient httpclient = new DefaultHttpClient();
try
{
HttpGet httpget = new HttpGet( nodeUri );
httpget.setHeader( "Accept", "*/*" );
HttpResponse response = httpclient.execute( httpget );
assertEquals( 404, response.getStatusLine().getStatusCode() );
}
finally
{
httpclient.getConnectionManager().shutdown();
}
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_DisableWADLDocIT.java
|
2,363
|
public class DatabaseMetadataServiceDocIT extends AbstractRestFunctionalTestBase
{
private static FunctionalTestHelper functionalTestHelper;
private static GraphDbHelper helper;
@BeforeClass
public static void setupServer() throws IOException
{
functionalTestHelper = new FunctionalTestHelper( server() );
helper = functionalTestHelper.getGraphDbHelper();
}
@Before
public void cleanTheDatabase()
{
cleanDatabase();
}
/**
* Get relationship types.
*/
@Documented
@Test
public void shouldReturn200OnGet()
{
helper.createRelationship( "KNOWS" );
helper.createRelationship( "LOVES" );
String result = gen.get()
.noGraph() // add back the graph when we have a clean graph really
.expectedStatus( 200 )
.get( functionalTestHelper.dataUri() + "relationship/types" )
.entity();
assertThat( result, allOf( containsString( "KNOWS" ), containsString( "LOVES" ) ) );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_DatabaseMetadataServiceDocIT.java
|
2,364
|
public class CypherDocIT extends AbstractRestFunctionalTestBase {
/**
* A simple query returning all nodes connected to some node, returning the
* node and the name property, if it exists, otherwise `NULL`:
*/
@Test
@Documented
@Title( "Send a query" )
@Graph( nodes = {
@NODE( name = "I", setNameProperty = true ),
@NODE( name = "you", setNameProperty = true ),
@NODE( name = "him", setNameProperty = true, properties = {
@PROP( key = "age", value = "25", type = GraphDescription.PropType.INTEGER ) } ) },
relationships = {
@REL( start = "I", end = "him", type = "know", properties = { } ),
@REL( start = "I", end = "you", type = "know", properties = { } ) } )
public void testPropertyColumn() throws UnsupportedEncodingException {
String script = createScript( "MATCH (x {name: 'I'})-[r]->(n) RETURN type(r), n.name, n.age" );
String response = cypherRestCall( script, Status.OK );
assertThat( response, containsString( "you" ) );
assertThat( response, containsString( "him" ) );
assertThat( response, containsString( "25" ) );
assertThat( response, not( containsString( "\"x\"" ) ) );
}
/**
* By passing in an additional GET parameter when you execute Cypher queries, metadata about the query will
* be returned, such as how many labels were added or removed by the query.
*/
@Test
@Documented
@Title( "Retrieve query metadata" )
@Graph( nodes = { @NODE( name = "I", setNameProperty = true, labels = { @LABEL( "Director" ) } ) } )
public void testQueryStatistics() throws JsonParseException
{
// Given
String script = createScript( "MATCH (n {name: 'I'}) SET n:Actor REMOVE n:Director RETURN labels(n)" );
// When
Map<String, Object> output = jsonToMap(doCypherRestCall( cypherUri() + "?includeStats=true", script, Status.OK ));
// Then
@SuppressWarnings("unchecked")
Map<String, Object> stats = (Map<String, Object>) output.get( "stats" );
assertThat( stats, isA( Map.class ) );
assertThat( (Boolean) stats.get( "contains_updates" ), is( true ) );
assertThat( (Integer) stats.get( "labels_added" ), is( 1 ) );
assertThat( (Integer) stats.get( "labels_removed" ), is( 1 ) );
assertThat( (Integer) stats.get( "nodes_created" ), is( 0 ) );
assertThat( (Integer) stats.get( "nodes_deleted" ), is( 0 ) );
assertThat( (Integer) stats.get( "properties_set" ), is( 0 ) );
assertThat( (Integer) stats.get( "relationships_created" ), is( 0 ) );
assertThat( (Integer) stats.get( "relationship_deleted" ), is( 0 ) );
}
/**
* Ensure that order of data and column is ok.
*/
@Test
@Graph( nodes = {
@NODE( name = "I", setNameProperty = true ),
@NODE( name = "you", setNameProperty = true ),
@NODE( name = "him", setNameProperty = true, properties = {
@PROP( key = "age", value = "25", type = GraphDescription.PropType.INTEGER ) } ) },
relationships = {
@REL( start = "I", end = "him", type = "know", properties = { } ),
@REL( start = "I", end = "you", type = "know", properties = { } ) } )
public void testDataColumnOrder() throws UnsupportedEncodingException {
String script = createScript( "START x = node(%I%) MATCH x -[r]-> n RETURN type(r), n.name, n.age" );
String response = cypherRestCall( script, Status.OK );
assertThat( response.indexOf( "columns" ) < response.indexOf( "data" ), is( true ));
}
/**
* Errors on the server will be reported as a JSON-formatted message,
* exception name and stacktrace.
*/
@Test
@Documented
@Title( "Errors" )
@Graph( "I know you" )
public void error_gets_returned_as_json() throws Exception {
String response = cypherRestCall( "MATCH (x {name: 'I'}) RETURN x.dummy/0", Status.BAD_REQUEST );
Map<String, Object> output = jsonToMap( response );
assertTrue( output.containsKey( "message" ) );
assertTrue( output.containsKey( "exception" ) );
assertTrue( output.containsKey( "stacktrace" ) );
}
/**
* Paths can be returned just like other return types.
*/
@Test
@Documented
@Title( "Return paths" )
@Graph( "I know you" )
public void return_paths() throws Exception {
String script = "MATCH path = (x {name: 'I'})--(friend) RETURN path, friend.name";
String response = cypherRestCall( script, Status.OK );
assertEquals( 2, ( jsonToMap( response ) ).size() );
assertThat( response, containsString( "data" ) );
assertThat( response, containsString( "you" ) );
}
/**
* Cypher supports queries with parameters
* which are submitted as JSON.
*/
@Test
@Documented
@Title("Use parameters")
@Graph( value = { "I know you" }, autoIndexNodes = true )
public void send_queries_with_parameters() throws Exception {
data.get();
String script = "MATCH (x {name: {startName}})-[r]-(friend) WHERE friend"
+ ".name = {name} RETURN TYPE(r)";
String response = cypherRestCall( script, Status.OK, Pair.of( "startName", "I" ), Pair.of( "name", "you" ) );
assertEquals( 2, ( jsonToMap( response ) ).size() );
assertTrue( response.contains( "know" ) );
assertTrue( response.contains( "data" ) );
}
/**
* Create a node with a label and a property using Cypher.
* See the request for the parameter sent with the query.
*/
@Test
@Documented
@Title( "Create a node" )
@Graph
public void send_query_to_create_a_node() throws Exception {
data.get();
String script = "CREATE (n:Person { name : {name} }) RETURN n";
String response = cypherRestCall( script, Status.OK, Pair.of( "name", "Andres" ) );
assertTrue( response.contains( "name" ) );
assertTrue( response.contains( "Andres" ) );
}
/**
* Create a node with a label and multiple properties using Cypher.
* See the request for the parameter sent with the query.
*/
@Test
@Documented
@Title( "Create a node with multiple properties" )
@Graph
public void send_query_to_create_a_node_from_a_map() throws Exception
{
data.get();
String script = "CREATE (n:Person { props } ) RETURN n";
String params = "\"props\" : { \"position\" : \"Developer\", \"name\" : \"Michael\", \"awesome\" : true, \"children\" : 3 }";
String response = cypherRestCall( script, Status.OK, params );
assertTrue( response.contains( "name" ) );
assertTrue( response.contains( "Michael" ) );
}
/**
* Create multiple nodes with properties using Cypher. See the request for
* the parameter sent with the query.
*/
@Test
@Documented
@Title( "Create mutiple nodes with properties" )
@Graph
public void send_query_to_create_multipe_nodes_from_a_map() throws Exception
{
data.get();
String script = "CREATE (n:Person { props } ) RETURN n";
String params = "\"props\" : [ { \"name\" : \"Andres\", \"position\" : \"Developer\" }, { \"name\" : \"Michael\", \"position\" : \"Developer\" } ]";
String response = cypherRestCall( script, Status.OK, params );
assertTrue( response.contains( "name" ) );
assertTrue( response.contains( "Michael" ) );
assertTrue( response.contains( "Andres" ) );
}
/**
* Set all properties on a node.
*/
@Test
@Documented
@Title( "Set all properties on a node using Cypher" )
@Graph
public void setAllPropertiesUsingMap() throws Exception
{
data.get();
String script = "CREATE (n:Person { name: 'this property is to be deleted' } ) SET n = { props } RETURN n";
String params = "\"props\" : { \"position\" : \"Developer\", \"firstName\" : \"Michael\", \"awesome\" : true, \"children\" : 3 }";
String response = cypherRestCall( script, Status.OK, params );
assertTrue( response.contains( "firstName" ) );
assertTrue( response.contains( "Michael" ) );
assertTrue( !response.contains( "name" ) );
assertTrue( !response.contains( "deleted" ) );
}
@Test
@Graph( nodes = {
@NODE( name = "I", properties = {
@PROP( key = "prop", value = "Hello", type = GraphDescription.PropType.STRING ) } ),
@NODE( name = "you" ) },
relationships = {
@REL( start = "I", end = "him", type = "know", properties = {
@PROP( key = "prop", value = "World", type = GraphDescription.PropType.STRING ) } ) } )
public void nodes_are_represented_as_nodes() throws Exception {
data.get();
String script = "START n = node(%I%) MATCH n-[r]->() RETURN n, r";
String response = cypherRestCall( script, Status.OK );
assertThat( response, containsString( "Hello" ) );
assertThat( response, containsString( "World" ) );
}
/**
* Sending a query with syntax errors will give a bad request (HTTP 400)
* response together with an error message.
*/
@Test
@Documented
@Title( "Syntax errors" )
@Graph( value = { "I know you" }, autoIndexNodes = true )
public void send_queries_with_syntax_errors() throws Exception {
data.get();
String script = "START x = node:node_auto_index(name={startName}) MATC path = (x-[r]-friend) WHERE friend"
+ ".name = {name} RETURN TYPE(r)";
String response = cypherRestCall( script, Status.BAD_REQUEST, Pair.of( "startName", "I" ), Pair.of( "name", "you" ) );
Map<String, Object> output = jsonToMap( response );
assertTrue( output.containsKey( "message" ) );
assertTrue( output.containsKey( "stacktrace" ) );
}
/**
* When sending queries that
* return nested results like list and maps,
* these will get serialized into nested JSON representations
* according to their types.
*/
@Test
@Documented
@Graph( value = { "I know you" }, autoIndexNodes = true )
public void nested_results() throws Exception {
data.get();
String script = "MATCH (n) WHERE n.name in ['I', 'you'] RETURN collect(n.name)";
String response = cypherRestCall(script, Status.OK);System.out.println();
Map<String, Object> resultMap = jsonToMap( response );
assertEquals( 2, resultMap.size() );
assertThat( response, anyOf( containsString( "\"I\",\"you\"" ), containsString(
"\"you\",\"I\"" ), containsString( "\"I\", \"you\"" ), containsString(
"\"you\", \"I\"" )) );
}
/**
* By passing in an extra parameter, you can ask the cypher executor to return a profile of the query
* as it is executed. This can help in locating bottlenecks.
*/
@Test
@Documented
@Title( "Profile a query" )
@Graph( nodes = {
@NODE( name = "I", setNameProperty = true ),
@NODE( name = "you", setNameProperty = true ),
@NODE( name = "him", setNameProperty = true, properties = {
@PROP( key = "age", value = "25", type = GraphDescription.PropType.INTEGER ) } ) },
relationships = {
@REL( start = "I", end = "him", type = "know", properties = { } ),
@REL( start = "I", end = "you", type = "know", properties = { } ) } )
public void testProfiling() throws Exception {
String script = createScript( "START x = node(%I%) MATCH x -[r]-> n RETURN type(r), n.name, n.age" );
// WHEN
String response = doCypherRestCall( cypherUri() + "?profile=true", script, Status.OK );
// THEN
Map<String, Object> des = jsonToMap( response );
assertThat( des.get( "plan" ), instanceOf( Map.class ));
@SuppressWarnings("unchecked")
Map<String, Object> plan = (Map<String, Object>)des.get( "plan" );
assertThat( plan.get( "name" ), instanceOf( String.class ) );
assertThat( plan.get( "children" ), instanceOf( Collection.class ));
assertThat( plan.get( "rows" ), instanceOf( Number.class ));
assertThat( plan.get( "dbHits" ), instanceOf( Number.class ));
}
@Test
@Graph( value = { "I know you" }, autoIndexNodes = false )
public void array_property() throws Exception {
setProperty("I", "array1", new int[] { 1, 2, 3 } );
setProperty("I", "array2", new String[] { "a", "b", "c" } );
String script = "START n = node(%I%) RETURN n.array1, n.array2";
String response = cypherRestCall( script, Status.OK );
assertThat( response, anyOf( containsString( "[ 1, 2, 3 ]" ), containsString( "[1,2,3]" )) );
assertThat( response, anyOf( containsString( "[ \"a\", \"b\", \"c\" ]" ),
containsString( "[\"a\",\"b\",\"c\"]" )) );
}
void setProperty(String nodeName, String propertyName, Object propertyValue) {
Node i = this.getNode(nodeName);
GraphDatabaseService db = i.getGraphDatabase();
try ( Transaction tx = db.beginTx() )
{
i.setProperty(propertyName, propertyValue);
tx.success();
}
}
/**
* This example shows what happens if you misspell
* an identifier.
*/
@Test
@Documented
@Title( "Send queries with errors" )
@Graph( value = { "I know you" }, autoIndexNodes = true )
public void send_queries_with_errors() throws Exception {
data.get();
String script = "START x = node:node_auto_index(name={startName}) MATCH path = (x-[r]-friend) WHERE frien"
+ ".name = {name} RETURN type(r)";
String response = cypherRestCall( script, Status.BAD_REQUEST, Pair.of( "startName", "I" ), Pair.of( "name", "you" ) );
Map<String, Object> responseMap = jsonToMap( response );
assertEquals( 4, responseMap.size() );
assertThat( response, containsString( "message" ) );
assertThat( ((String) responseMap.get( "message" )), containsString( "frien not defined" ) );
}
@SafeVarargs
private final String cypherRestCall( String script, Status status, Pair<String, String>... params )
{
return doCypherRestCall( cypherUri(), script, status, params );
}
private String cypherRestCall( String script, Status status, String paramString )
{
return doCypherRestCall( cypherUri(), script, status, paramString );
}
private String cypherUri()
{
return getDataUri() + "cypher";
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_CypherDocIT.java
|
2,365
|
public class CreateRelationshipDocTest extends
AbstractRestFunctionalTestBase
{
/**
* Upon successful creation of a relationship, the new relationship is
* returned.
*/
@Test
@Graph( "Joe knows Sara" )
@Documented
@Title( "Create a relationship with properties" )
public void create_a_relationship_with_properties() throws Exception
{
String jsonString = "{\"to\" : \""
+ getDataUri()
+ "node/"
+ getNode( "Sara" ).getId()
+ "\", \"type\" : \"LOVES\", \"data\" : {\"foo\" : \"bar\"}}";
Node i = getNode( "Joe" );
gen.get().description( startGraph( "Add relationship with properties before" ) );
gen.get().expectedStatus(
Status.CREATED.getStatusCode() ).payload( jsonString ).post(
getNodeUri( i ) + "/relationships" );
try ( Transaction tx = graphdb().beginTx() )
{
assertTrue( i.hasRelationship( DynamicRelationshipType.withName( "LOVES" ) ) );
}
}
/**
* Upon successful creation of a relationship, the new relationship is
* returned.
*/
@Test
@Documented
@Title( "Create relationship" )
@Graph( "Joe knows Sara" )
public void create_relationship() throws Exception
{
String jsonString = "{\"to\" : \""
+ getDataUri()
+ "node/"
+ getNode( "Sara" ).getId()
+ "\", \"type\" : \"LOVES\"}";
Node i = getNode( "Joe" );
String entity = gen.get().expectedStatus(
Status.CREATED.getStatusCode() ).payload( jsonString ).post(
getNodeUri( i ) + "/relationships" ).entity();
try ( Transaction tx = graphdb().beginTx() )
{
assertTrue( i.hasRelationship( DynamicRelationshipType.withName( "LOVES" ) ) );
}
assertProperRelationshipRepresentation( JsonHelper.jsonToMap( entity ) );
}
@Test
@Graph( "Joe knows Sara" )
public void shouldRespondWith404WhenStartNodeDoesNotExist()
{
String jsonString = "{\"to\" : \""
+ getDataUri()
+ "node/"
+ getNode( "Joe" )
+ "\", \"type\" : \"LOVES\", \"data\" : {\"foo\" : \"bar\"}}";
gen.get().expectedStatus(
Status.NOT_FOUND.getStatusCode() ).expectedType( MediaType.TEXT_HTML_TYPE ).payload( jsonString ).post(
getDataUri() + "/node/12345/relationships" ).entity();
}
@Test
@Graph( "Joe knows Sara" )
public void creating_a_relationship_to_a_nonexisting_end_node()
{
String jsonString = "{\"to\" : \""
+ getDataUri()
+ "node/"
+ "999999\", \"type\" : \"LOVES\", \"data\" : {\"foo\" : \"bar\"}}";
gen.get().expectedStatus(
Status.BAD_REQUEST.getStatusCode() ).payload( jsonString ).post(
getNodeUri( getNode( "Joe" ) ) + "/relationships" ).entity();
}
@Test
@Graph( "Joe knows Sara" )
public void creating_a_loop_relationship()
throws Exception
{
Node joe = getNode( "Joe" );
String jsonString = "{\"to\" : \"" + getNodeUri( joe )
+ "\", \"type\" : \"LOVES\"}";
String entity = gen.get().expectedStatus(
Status.CREATED.getStatusCode() ).payload( jsonString ).post(
getNodeUri( getNode( "Joe" ) ) + "/relationships" ).entity();
assertProperRelationshipRepresentation( JsonHelper.jsonToMap( entity ) );
}
@Test
@Graph( "Joe knows Sara" )
public void providing_bad_JSON()
{
String jsonString = "{\"to\" : \""
+ getNodeUri( data.get().get( "Joe" ) )
+ "\", \"type\" : \"LOVES\", \"data\" : {\"foo\" : **BAD JSON HERE*** \"bar\"}}";
gen.get().expectedStatus(
Status.BAD_REQUEST.getStatusCode() ).payload( jsonString ).post(
getNodeUri( getNode( "Joe" ) ) + "/relationships" ).entity();
}
private void assertProperRelationshipRepresentation(
Map<String, Object> relrep )
{
RelationshipRepresentationTest.verifySerialisation( relrep );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_CreateRelationshipDocTest.java
|
2,366
|
public class ConsoleDocTest extends AbstractRestFunctionalTestBase
{
/**
* Paths can be returned
* together with other return types by just
* specifying returns.
*/
@Test
@Documented
@Graph( "I know you" )
public void testShell() throws Exception {
String command = "ls";
String response = shellCall(command, Status.OK);
assertEquals( 2, ( JsonHelper.jsonToList( response ) ).size() );
}
private String shellCall(String command, Status status,
Pair<String, String>... params)
{
return gen().payload("{\"command\":\""+command+"\",\"engine\":\"shell\"}").expectedStatus(status.getStatusCode()).post(consoleUri() ).entity();
}
private String consoleUri()
{
return getDatabaseUri() + "manage/server/console";
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_ConsoleDocTest.java
|
2,367
|
public class ConfigureBaseUriDocIT extends AbstractRestFunctionalTestBase
{
private static FunctionalTestHelper functionalTestHelper;
@BeforeClass
public static void setupServer() throws IOException
{
functionalTestHelper = new FunctionalTestHelper( server() );
}
@Before
public void setupTheDatabase()
{
cleanDatabase();
}
@Test
public void shouldForwardHttpAndHost() throws Exception
{
URI rootUri = functionalTestHelper.baseUri();
HttpClient httpclient = new DefaultHttpClient();
try
{
HttpGet httpget = new HttpGet( rootUri );
httpget.setHeader( "Accept", "application/json" );
httpget.setHeader( "X-Forwarded-Host", "foobar.com" );
httpget.setHeader( "X-Forwarded-Proto", "http" );
HttpResponse response = httpclient.execute( httpget );
String length = response.getHeaders( "CONTENT-LENGTH" )[0].getValue();
byte[] data = new byte[Integer.valueOf( length )];
response.getEntity().getContent().read( data );
String responseEntityBody = new String( data );
assertTrue( responseEntityBody.contains( "http://foobar.com" ) );
assertFalse( responseEntityBody.contains( "localhost" ) );
}
finally
{
httpclient.getConnectionManager().shutdown();
}
}
@Test
public void shouldForwardHttpsAndHost() throws Exception
{
URI rootUri = functionalTestHelper.baseUri();
HttpClient httpclient = new DefaultHttpClient();
try
{
HttpGet httpget = new HttpGet( rootUri );
httpget.setHeader( "Accept", "application/json" );
httpget.setHeader( "X-Forwarded-Host", "foobar.com" );
httpget.setHeader( "X-Forwarded-Proto", "https" );
HttpResponse response = httpclient.execute( httpget );
String length = response.getHeaders( "CONTENT-LENGTH" )[0].getValue();
byte[] data = new byte[Integer.valueOf( length )];
response.getEntity().getContent().read( data );
String responseEntityBody = new String( data );
assertTrue( responseEntityBody.contains( "https://foobar.com" ) );
assertFalse( responseEntityBody.contains( "localhost" ) );
}
finally
{
httpclient.getConnectionManager().shutdown();
}
}
@Test
public void shouldForwardHttpAndHostOnDifferentPort() throws Exception
{
URI rootUri = functionalTestHelper.baseUri();
HttpClient httpclient = new DefaultHttpClient();
try
{
HttpGet httpget = new HttpGet( rootUri );
httpget.setHeader( "Accept", "application/json" );
httpget.setHeader( "X-Forwarded-Host", "foobar.com:9999" );
httpget.setHeader( "X-Forwarded-Proto", "http" );
HttpResponse response = httpclient.execute( httpget );
String length = response.getHeaders( "CONTENT-LENGTH" )[0].getValue();
byte[] data = new byte[Integer.valueOf( length )];
response.getEntity().getContent().read( data );
String responseEntityBody = new String( data );
assertTrue( responseEntityBody.contains( "http://foobar.com:9999" ) );
assertFalse( responseEntityBody.contains( "localhost" ) );
}
finally
{
httpclient.getConnectionManager().shutdown();
}
}
@Test
public void shouldForwardHttpAndFirstHost() throws Exception
{
URI rootUri = functionalTestHelper.baseUri();
HttpClient httpclient = new DefaultHttpClient();
try
{
HttpGet httpget = new HttpGet( rootUri );
httpget.setHeader( "Accept", "application/json" );
httpget.setHeader( "X-Forwarded-Host", "foobar.com, bazbar.com" );
httpget.setHeader( "X-Forwarded-Proto", "http" );
HttpResponse response = httpclient.execute( httpget );
String length = response.getHeaders( "CONTENT-LENGTH" )[0].getValue();
byte[] data = new byte[Integer.valueOf( length )];
response.getEntity().getContent().read( data );
String responseEntityBody = new String( data );
assertTrue( responseEntityBody.contains( "http://foobar.com" ) );
assertFalse( responseEntityBody.contains( "localhost" ) );
}
finally
{
httpclient.getConnectionManager().shutdown();
}
}
@Test
public void shouldForwardHttpsAndHostOnDifferentPort() throws Exception
{
URI rootUri = functionalTestHelper.baseUri();
HttpClient httpclient = new DefaultHttpClient();
try
{
HttpGet httpget = new HttpGet( rootUri );
httpget.setHeader( "Accept", "application/json" );
httpget.setHeader( "X-Forwarded-Host", "foobar.com:9999" );
httpget.setHeader( "X-Forwarded-Proto", "https" );
HttpResponse response = httpclient.execute( httpget );
String length = response.getHeaders( "CONTENT-LENGTH" )[0].getValue();
byte[] data = new byte[Integer.valueOf( length )];
response.getEntity().getContent().read( data );
String responseEntityBody = new String( data );
assertTrue( responseEntityBody.contains( "https://foobar.com:9999" ) );
assertFalse( responseEntityBody.contains( "localhost" ) );
}
finally
{
httpclient.getConnectionManager().shutdown();
}
}
@Test
public void shouldUseRequestUriWhenNoXForwardHeadersPresent() throws Exception
{
URI rootUri = functionalTestHelper.baseUri();
HttpClient httpclient = new DefaultHttpClient();
try
{
HttpGet httpget = new HttpGet( rootUri );
httpget.setHeader( "Accept", "application/json" );
HttpResponse response = httpclient.execute( httpget );
String length = response.getHeaders( "CONTENT-LENGTH" )[0].getValue();
byte[] data = new byte[Integer.valueOf( length )];
response.getEntity().getContent().read( data );
String responseEntityBody = new String( data );
assertFalse( responseEntityBody.contains( "https://foobar.com" ) );
assertFalse( responseEntityBody.contains( ":0" ) );
assertTrue( responseEntityBody.contains( "localhost" ) );
}
finally
{
httpclient.getConnectionManager().shutdown();
}
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_ConfigureBaseUriDocIT.java
|
2,368
|
public class CompactJsonDocIT extends AbstractRestFunctionalTestBase
{
private long thomasAnderson;
private long trinity;
private long thomasAndersonLovesTrinity;
private static FunctionalTestHelper functionalTestHelper;
private static GraphDbHelper helper;
@BeforeClass
public static void setupServer() throws IOException
{
functionalTestHelper = new FunctionalTestHelper( server() );
helper = functionalTestHelper.getGraphDbHelper();
}
@Before
public void setupTheDatabase()
{
cleanDatabase();
createTheMatrix();
}
private void createTheMatrix()
{
// Create the matrix example
thomasAnderson = createAndIndexNode( "Thomas Anderson" );
trinity = createAndIndexNode( "Trinity" );
long tank = createAndIndexNode( "Tank" );
long knowsRelationshipId = helper.createRelationship( "KNOWS", thomasAnderson, trinity );
thomasAndersonLovesTrinity = helper.createRelationship( "LOVES", thomasAnderson, trinity );
helper.setRelationshipProperties( thomasAndersonLovesTrinity,
Collections.singletonMap( "strength", (Object) 100 ) );
helper.createRelationship( "KNOWS", thomasAnderson, tank );
helper.createRelationship( "KNOWS", trinity, tank );
// index a relationship
helper.createRelationshipIndex( "relationships" );
helper.addRelationshipToIndex( "relationships", "key", "value", knowsRelationshipId );
// index a relationship
helper.createRelationshipIndex( "relationships2" );
helper.addRelationshipToIndex( "relationships2", "key2", "value2", knowsRelationshipId );
}
private long createAndIndexNode( String name )
{
long id = helper.createNode();
helper.setNodeProperties( id, Collections.singletonMap( "name", (Object) name ) );
helper.addNodeToIndex( "node", "name", name, id );
return id;
}
@Test
public void shouldGetThomasAndersonDirectly() {
JaxRsResponse response = RestRequest.req().get(functionalTestHelper.nodeUri(thomasAnderson), CompactJsonFormat.MEDIA_TYPE);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.getEntity();
assertTrue(entity.contains("Thomas Anderson"));
assertValidJson(entity);
response.close();
}
private void assertValidJson( String entity )
{
try
{
assertTrue( JsonHelper.jsonToMap( entity )
.containsKey( "self" ) );
assertFalse( JsonHelper.jsonToMap( entity )
.containsKey( "properties" ) );
}
catch ( JsonParseException e )
{
e.printStackTrace();
}
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_CompactJsonDocIT.java
|
2,369
|
public class BatchOperationDocIT extends AbstractRestFunctionalTestBase
{
/**
* Execute multiple operations in batch.
*
* This lets you execute multiple API calls through a single HTTP call,
* significantly improving performance for large insert and update
* operations.
*
* The batch service expects an array of job descriptions as input, each job
* description describing an action to be performed via the normal server
* API.
*
* This service is transactional. If any of the operations performed fails
* (returns a non-2xx HTTP status code), the transaction will be rolled back
* and all changes will be undone.
*
* Each job description should contain a +to+ attribute, with a value
* relative to the data API root (so http://localhost:7474/db/data/node becomes
* just /node), and a +method+ attribute containing HTTP verb to use.
*
* Optionally you may provide a +body+ attribute, and an +id+ attribute to
* help you keep track of responses, although responses are guaranteed to be
* returned in the same order the job descriptions are received.
*
* The following figure outlines the different parts of the job
* descriptions:
*
* image::batch-request-api.png[]
*/
@Documented
@SuppressWarnings( "unchecked" )
@Test
@Graph("Joe knows John")
public void shouldPerformMultipleOperations() throws Exception
{
long idJoe = data.get().get( "Joe" ).getId();
String jsonString = new PrettyJSON()
.array()
.object()
.key("method") .value("PUT")
.key("to") .value("/node/" + idJoe + "/properties")
.key("body")
.object()
.key("age").value(1)
.endObject()
.key("id") .value(0)
.endObject()
.object()
.key("method") .value("GET")
.key("to") .value("/node/" + idJoe)
.key("id") .value(1)
.endObject()
.object()
.key("method") .value("POST")
.key("to") .value("/node")
.key("body")
.object()
.key("age").value(1)
.endObject()
.key("id") .value(2)
.endObject()
.object()
.key("method") .value("POST")
.key("to") .value("/node")
.key("body")
.object()
.key("age").value(1)
.endObject()
.key("id") .value(3)
.endObject()
.endArray().toString();
String entity = gen.get()
.payload(jsonString)
.expectedStatus(200)
.post(batchUri()).entity();
List<Map<String, Object>> results = JsonHelper.jsonToList(entity);
assertEquals(4, results.size());
Map<String, Object> putResult = results.get(0);
Map<String, Object> getResult = results.get(1);
Map<String, Object> firstPostResult = results.get(2);
Map<String, Object> secondPostResult = results.get(3);
// Ids should be ok
assertEquals(0, putResult.get("id"));
assertEquals(2, firstPostResult.get("id"));
assertEquals(3, secondPostResult.get("id"));
// Should contain "from"
assertEquals("/node/"+idJoe+"/properties", putResult.get("from"));
assertEquals("/node/"+idJoe, getResult.get("from"));
assertEquals("/node", firstPostResult.get("from"));
assertEquals("/node", secondPostResult.get("from"));
// Post should contain location
assertTrue(((String) firstPostResult.get("location")).length() > 0);
assertTrue(((String) secondPostResult.get("location")).length() > 0);
// Should have created by the first PUT request
Map<String, Object> body = (Map<String, Object>) getResult.get("body");
assertEquals(1, ((Map<String, Object>) body.get("data")).get("age"));
}
/**
* Refer to items created earlier in the same batch job.
*
* The batch operation API allows you to refer to the URI returned from a
* created resource in subsequent job descriptions, within the same batch
* call.
*
* Use the +{[JOB ID]}+ special syntax to inject URIs from created resources
* into JSON strings in subsequent job descriptions.
*/
@Documented
@Test
public void shouldBeAbleToReferToCreatedResource() throws Exception
{
String jsonString = new PrettyJSON()
.array()
.object()
.key("method") .value("POST")
.key("to") .value("/node")
.key("id") .value(0)
.key("body")
.object()
.key("name").value("bob")
.endObject()
.endObject()
.object()
.key("method") .value("POST")
.key("to") .value("/node")
.key("id") .value(1)
.key("body")
.object()
.key("age").value(12)
.endObject()
.endObject()
.object()
.key("method") .value("POST")
.key("to") .value("{0}/relationships")
.key("id") .value(3)
.key("body")
.object()
.key("to").value("{1}")
.key("data")
.object()
.key("since").value("2010")
.endObject()
.key("type").value("KNOWS")
.endObject()
.endObject()
.object()
.key("method") .value("POST")
.key("to") .value("/index/relationship/my_rels")
.key("id") .value(4)
.key("body")
.object()
.key("key").value("since")
.key("value").value("2010")
.key("uri").value("{3}")
.endObject()
.endObject()
.endArray().toString();
String entity = gen.get()
.expectedStatus( 200 )
.payload( jsonString )
.post( batchUri() )
.entity();
List<Map<String, Object>> results = JsonHelper.jsonToList(entity);
assertEquals(4, results.size());
// String rels = gen.get()
// .expectedStatus( 200 ).get( getRelationshipIndexUri( "my_rels", "since", "2010")).entity();
// assertEquals(1, JsonHelper.jsonToList( rels ).size());
}
private String batchUri()
{
return getDataUri()+"batch";
}
@Test
public void shouldGetLocationHeadersWhenCreatingThings() throws Exception
{
int originalNodeCount = countNodes();
final String jsonString = new PrettyJSON()
.array()
.object()
.key("method").value("POST")
.key("to").value("/node")
.key("body")
.object()
.key("age").value(1)
.endObject()
.endObject()
.endArray().toString();
JaxRsResponse response = RestRequest.req().post(batchUri(), jsonString);
assertEquals(200, response.getStatus());
assertEquals(originalNodeCount + 1, countNodes());
List<Map<String, Object>> results = JsonHelper.jsonToList(response.getEntity());
assertEquals(1, results.size());
Map<String, Object> result = results.get(0);
assertTrue(((String) result.get("location")).length() > 0);
}
@Test
public void shouldForwardUnderlyingErrors() throws Exception
{
JaxRsResponse response = RestRequest.req().post(batchUri(), new PrettyJSON()
.array()
.object()
.key("method") .value("POST")
.key("to") .value("/node")
.key("body")
.object()
.key("age")
.array()
.value(true)
.value("hello")
.endArray()
.endObject()
.endObject()
.endArray()
.toString());
assertEquals(500, response.getStatus());
Map<String, Object> res = JsonHelper.jsonToMap(response.getEntity());
assertTrue(((String)res.get("message")).startsWith("Invalid JSON array in POST body"));
}
@Test
public void shouldRollbackAllWhenGivenIncorrectRequest() throws ClientHandlerException,
UniformInterfaceException, JSONException
{
String jsonString = new PrettyJSON()
.array()
.object()
.key("method") .value("POST")
.key("to") .value("/node")
.key("body")
.object()
.key("age").value("1")
.endObject()
.endObject()
.object()
.key("method") .value("POST")
.key("to") .value("/node")
.key("body")
.array()
.value("a_list")
.value("this_makes_no_sense")
.endArray()
.endObject()
.endArray()
.toString();
int originalNodeCount = countNodes();
JaxRsResponse response = RestRequest.req().post(batchUri(), jsonString);
assertEquals(500, response.getStatus());
assertEquals(originalNodeCount, countNodes());
}
@Test
@SuppressWarnings("unchecked")
public void shouldHandleUnicodeGetCorrectly() throws Exception
{
String asianText = "\u4f8b\u5b50";
String germanText = "öäüÖÄÜß";
String complicatedString = asianText + germanText;
String jsonString = new PrettyJSON()
.array()
.object()
.key("method") .value("POST")
.key("to") .value("/node")
.key("body") .object()
.key(complicatedString).value(complicatedString)
.endObject()
.endObject()
.endArray()
.toString();
String entity = gen.get()
.expectedStatus( 200 )
.payload( jsonString )
.post( batchUri() )
.entity();
// Pull out the property value from the depths of the response
Map<String, Object> response = (Map<String, Object>) JsonHelper.jsonToList(entity).get(0).get("body");
String returnedValue = (String)((Map<String,Object>)response.get("data")).get(complicatedString);
// Ensure nothing was borked.
assertThat("Expected twisted unicode case to work, but response was: " + entity,
returnedValue, is(complicatedString));
}
@Test
public void shouldHandleFailingCypherStatementCorrectly() throws Exception
{
String jsonString = new PrettyJSON()
.array()
.object()
.key("method") .value("POST")
.key("to") .value("/cypher")
.key("body") .object()
.key("query").value("start n=node({id}) set n.foo = 10 return n")
.key("params").object().key("id").value("0").endObject()
.endObject()
.endObject()
.object()
.key("method") .value("POST")
.key("to") .value("/node")
.endObject()
.endArray()
.toString();
String entity = gen.get()
.expectedStatus( 500 )
.payload( jsonString )
.post( batchUri() )
.entity();
// Pull out the property value from the depths of the response
Map<String, Object> result = JsonHelper.jsonToMap(entity);
String exception = (String) result.get("exception");
assertThat(exception, is("BatchOperationFailedException"));
String innerException = (String) ((Map) JsonHelper.jsonToMap((String) result.get("message"))).get("exception");
assertThat(innerException, is("CypherTypeException"));
}
@Test
@Graph("Peter likes Jazz")
public void shouldHandleEscapedStrings() throws ClientHandlerException,
UniformInterfaceException, JSONException, PropertyValueException
{
String string = "Jazz";
Node gnode = getNode( string );
assertThat( gnode, inTx(graphdb(), hasProperty( "name" ).withValue(string)) );
String name = "string\\ and \"test\"";
String jsonString = new PrettyJSON()
.array()
.object()
.key("method") .value("PUT")
.key("to") .value("/node/"+gnode.getId()+"/properties")
.key("body")
.object()
.key("name").value(name)
.endObject()
.endObject()
.endArray()
.toString();
gen.get()
.expectedStatus( 200 )
.payload( jsonString )
.post( batchUri() )
.entity();
jsonString = new PrettyJSON()
.array()
.object()
.key("method") .value("GET")
.key("to") .value("/node/"+gnode.getId()+"/properties/name")
.endObject()
.endArray()
.toString();
String entity = gen.get()
.expectedStatus( 200 )
.payload( jsonString )
.post( batchUri() )
.entity();
List<Map<String, Object>> results = JsonHelper.jsonToList(entity);
assertEquals(results.get(0).get("body"), name);
}
@Test
public void shouldRollbackAllWhenInsertingIllegalData() throws ClientHandlerException,
UniformInterfaceException, JSONException
{
String jsonString = new PrettyJSON()
.array()
.object()
.key("method") .value("POST")
.key("to") .value("/node")
.key("body")
.object()
.key("age").value(1)
.endObject()
.endObject()
.object()
.key("method").value("POST")
.key("to").value("/node")
.key("body")
.object()
.key("age")
.object()
.key("age").value(1)
.endObject()
.endObject()
.endObject()
.endArray().toString();
int originalNodeCount = countNodes();
JaxRsResponse response = RestRequest.req().post(batchUri(), jsonString);
assertEquals(500, response.getStatus());
assertEquals(originalNodeCount, countNodes());
}
@Test
public void shouldRollbackAllOnSingle404() throws ClientHandlerException,
UniformInterfaceException, JSONException
{
String jsonString = new PrettyJSON()
.array()
.object()
.key("method") .value("POST")
.key("to") .value("/node")
.key("body")
.object()
.key("age").value(1)
.endObject()
.endObject()
.object()
.key("method") .value("POST")
.key("to") .value("www.google.com")
.endObject()
.endArray().toString();
int originalNodeCount = countNodes();
JaxRsResponse response = RestRequest.req().post(batchUri(), jsonString);
assertEquals(500, response.getStatus());
assertEquals(originalNodeCount, countNodes());
}
@Test
public void shouldBeAbleToReferToUniquelyCreatedEntities() throws Exception
{
String jsonString = new PrettyJSON()
.array()
.object()
.key("method") .value("POST")
.key("to") .value("/index/node/Cultures?unique")
.key("body")
.object()
.key("key").value("ID")
.key("value").value("fra")
.key("properties")
.object()
.key("ID").value("fra")
.endObject()
.endObject()
.key("id") .value(0)
.endObject()
.object()
.key("method") .value("POST")
.key("to") .value("/node")
.key("id") .value(1)
.endObject()
.object()
.key("method") .value("POST")
.key("to") .value("{1}/relationships")
.key("body")
.object()
.key("to").value("{0}")
.key("type").value("has")
.endObject()
.key("id") .value(2)
.endObject()
.endArray().toString();
JaxRsResponse response = RestRequest.req().post(batchUri(), jsonString);
assertEquals(200, response.getStatus());
}
@Test
public void shouldNotFailWhenRemovingAndAddingLabelsInOneBatch() throws Exception
{
// given
/*
curl -X POST http://localhost:7474/db/data/batch -H 'Content-Type: application/json'
-d '[
{"body":{"name":"Alice"},"to":"node","id":0,"method":"POST"},
{"body":["expert","coder"],"to":"{0}/labels","id":1,"method":"POST"},
{"body":["novice","chef"],"to":"{0}/labels","id":2,"method":"PUT"}
]'
*/
String jsonString = new PrettyJSON()
.array()
.object()
.key("method") .value("POST")
.key("to") .value("node")
.key("id") .value(0)
.key("body")
.object()
.key("key").value("name")
.key("value").value("Alice")
.endObject()
.endObject()
.object()
.key("method") .value("POST")
.key("to") .value("{0}/labels")
.key("id") .value(1)
.key("body")
.array()
.value( "expert" )
.value( "coder" )
.endArray()
.endObject()
.object()
.key("method") .value("PUT")
.key("to") .value("{0}/labels")
.key("id") .value(2)
.key("body")
.array()
.value( "novice" )
.value( "chef" )
.endArray()
.endObject()
.endArray().toString();
// when
JaxRsResponse response = RestRequest.req().post(batchUri(), jsonString);
// then
assertEquals(200, response.getStatus());
}
// It has to be possible to create relationships among created and not-created nodes
// in batch operation. Tests the fix for issue #690.
@Test
public void shouldBeAbleToReferToNotCreatedUniqueEntities() throws Exception
{
String jsonString = new PrettyJSON()
.array()
.object()
.key("method") .value("POST")
.key("to") .value("/index/node/Cultures?unique")
.key("body")
.object()
.key("key").value("name")
.key("value").value("tobias")
.key("properties")
.object()
.key("name").value("Tobias Tester")
.endObject()
.endObject()
.key("id") .value(0)
.endObject()
.object() // Creates Andres, hence 201 Create
.key("method") .value("POST")
.key("to") .value("/index/node/Cultures?unique")
.key("body")
.object()
.key("key").value("name")
.key("value").value("andres")
.key("properties")
.object()
.key("name").value("Andres Tester")
.endObject()
.endObject()
.key("id") .value(1)
.endObject()
.object() // Duplicated to ID.1, hence 200 OK
.key("method") .value("POST")
.key("to") .value("/index/node/Cultures?unique")
.key("body")
.object()
.key("key").value("name")
.key("value").value("andres")
.key("properties")
.object()
.key("name").value("Andres Tester")
.endObject()
.endObject()
.key("id") .value(2)
.endObject()
.object()
.key("method") .value("POST")
.key("to") .value("/index/relationship/my_rels/?unique")
.key("body")
.object()
.key("key").value("name")
.key("value").value("tobias-andres")
.key("start").value("{0}")
.key("end").value("{1}")
.key("type").value("FRIENDS")
.endObject()
.key("id") .value(3)
.endObject()
.object()
.key("method") .value("POST")
.key("to") .value("/index/relationship/my_rels/?unique")
.key("body")
.object()
.key("key").value("name")
.key("value").value("andres-tobias")
.key("start").value("{2}") // Not-created entity here
.key("end").value("{0}")
.key("type").value("FRIENDS")
.endObject()
.key("id") .value(4)
.endObject()
.object()
.key("method") .value("POST")
.key("to") .value("/index/relationship/my_rels/?unique")
.key("body")
.object()
.key("key").value("name")
.key("value").value("andres-tobias")
.key("start").value("{1}") // Relationship should not be created
.key("end").value("{0}")
.key("type").value("FRIENDS")
.endObject()
.key("id") .value(5)
.endObject()
.endArray().toString();
JaxRsResponse response = RestRequest.req().post(batchUri(), jsonString);
assertEquals(200, response.getStatus());
final String entity = response.getEntity();
List<Map<String, Object>> results = JsonHelper.jsonToList(entity);
assertEquals(6, results.size());
Map<String, Object> andresResult1 = results.get(1);
Map<String, Object> andresResult2 = results.get(2);
Map<String, Object> secondRelationship = results.get(4);
Map<String, Object> thirdRelationship = results.get(5);
// Same people
Map<String, Object> body1 = (Map<String, Object>) andresResult1.get("body");
Map<String, Object> body2 = (Map<String, Object>) andresResult2.get("body");
assertEquals(body1.get("id"), body2.get("id"));
// Same relationship
body1 = (Map<String, Object>) secondRelationship.get("body");
body2 = (Map<String, Object>) thirdRelationship.get("body");
assertEquals(body1.get("self"), body2.get("self"));
// Created for {2} {0}
assertTrue(((String) secondRelationship.get("location")).length() > 0);
// {2} = {1} = Andres
body1 = (Map<String, Object>) secondRelationship.get("body");
body2 = (Map<String, Object>) andresResult1.get("body");
assertEquals(body1.get("start"), body2.get("self"));
}
private int countNodes()
{
try ( Transaction tx = graphdb().beginTx() )
{
int count = 0;
for(Node node : GlobalGraphOperations.at(graphdb()).getAllNodes())
{
count++;
}
return count;
}
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_BatchOperationDocIT.java
|
2,370
|
public class AutoIndexWithNonDefaultConfigurationThroughRESTAPIDocIT extends ExclusiveServerTestBase
{
private static CommunityNeoServer server;
private static FunctionalTestHelper functionalTestHelper;
@ClassRule
public static TemporaryFolder staticFolder = new TemporaryFolder();
public
@Rule
TestData<RESTDocsGenerator> gen = TestData.producedThrough( RESTDocsGenerator.PRODUCER );
@Before
public void setUp()
{
gen.get().setSection( "dev/rest-api" );
}
@BeforeClass
public static void allocateServer() throws IOException
{
server = CommunityServerBuilder.server()
.usingDatabaseDir( staticFolder.getRoot().getAbsolutePath() )
.withAutoIndexingEnabledForNodes( "foo", "bar" )
.build();
server.start();
functionalTestHelper = new FunctionalTestHelper( server );
}
@Before
public void cleanTheDatabase()
{
ServerHelper.cleanTheDatabase( server );
}
@AfterClass
public static void stopServer()
{
server.stop();
}
/**
* Create an auto index for nodes with specific configuration.
*/
@Documented
@Test
public void shouldCreateANodeAutoIndexWithGivenFullTextConfiguration() throws Exception
{
String responseBody = gen.get()
.expectedStatus( 201 )
.payload( "{\"name\":\"node_auto_index\", \"config\":{\"type\":\"fulltext\",\"provider\":\"lucene\"}}" )
.post( functionalTestHelper.nodeIndexUri() )
.entity();
assertThat( responseBody, containsString( "\"type\" : \"fulltext\"" ) );
}
/**
* Create an auto index for relationships with specific configuration.
*/
@Documented
@Test
public void shouldCreateARelationshipAutoIndexWithGivenFullTextConfiguration() throws Exception
{
String responseBody = gen.get()
.expectedStatus( 201 )
.payload(
"{\"name\":\"relationship_auto_index\", \"config\":{\"type\":\"fulltext\"," +
"\"provider\":\"lucene\"}}" )
.post( functionalTestHelper.relationshipIndexUri() )
.entity();
assertThat( responseBody, containsString( "\"type\" : \"fulltext\"" ) );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_AutoIndexWithNonDefaultConfigurationThroughRESTAPIDocIT.java
|
2,371
|
public class AutoIndexDocIT extends AbstractRestFunctionalTestBase
{
/**
* Find node by query from an automatic index.
*
* See Find node by query for the actual query syntax.
*/
@Documented
@Test
@Graph( nodes = { @NODE( name = "I", setNameProperty = true ) }, autoIndexNodes = true )
public void shouldRetrieveFromAutoIndexByQuery()
{
data.get();
assertSize( 1, gen.get()
.noGraph()
.expectedStatus( 200 )
.get( nodeAutoIndexUri() + "?query=name:I" )
.entity() );
}
private String nodeAutoIndexUri()
{
return getDataUri() + "index/auto/node/";
}
/**
* Automatic index nodes can be found via exact lookups with normal Index
* REST syntax.
*/
@Documented
@Test
@Graph( nodes = { @NODE( name = "I", setNameProperty = true ) }, autoIndexNodes = true )
public void find_node_by_exact_match_from_an_automatic_index()
{
data.get();
assertSize( 1, gen.get()
.noGraph()
.expectedStatus( 200 )
.get( nodeAutoIndexUri() + "name/I" )
.entity() );
}
/**
* The automatic relationship index can not be removed.
*/
@Test
@Documented
@Title( "Relationship AutoIndex is not removable" )
@Graph( nodes = { @NODE( name = "I", setNameProperty = true ) }, autoIndexNodes = true )
public void Relationship_AutoIndex_is_not_removable()
{
data.get();
gen.get()
.noGraph()
.expectedStatus( 405 )
.delete( relationshipAutoIndexUri() )
.entity();
}
/**
* The automatic node index can not be removed.
*/
@Test
@Documented
@Title( "Node AutoIndex is not removable" )
@Graph( nodes = { @NODE( name = "I", setNameProperty = true ) }, autoIndexNodes = true )
public void AutoIndex_is_not_removable()
{
gen.get()
.noGraph()
.expectedStatus( 405 )
.delete( nodeAutoIndexUri() )
.entity();
}
/**
* It is not allowed to add items manually to automatic indexes.
*/
@Test
@Graph( nodes = { @NODE( name = "I", setNameProperty = true ) }, autoIndexNodes = true )
@Documented
@Title( "Items can not be added manually to an node AutoIndex" )
public void items_can_not_be_added_manually_to_an_AutoIndex() throws Exception
{
data.get();
String indexName = graphdb().index()
.getNodeAutoIndexer()
.getAutoIndex()
.getName();
gen.get()
.noGraph()
.expectedStatus( 405 )
.payload( createJsonStringFor( getNodeUri( data.get()
.get( "I" ) ), "name", "I" ) )
.post( postNodeIndexUri( indexName ) )
.entity();
}
private String createJsonStringFor( final String targetUri, final String key, final String value )
{
return "{\"key\": \"" + key + "\", \"value\": \"" + value + "\", \"uri\": \"" + targetUri + "\"}";
}
/**
* It is not allowed to add items manually to automatic indexes.
*/
@Test
@Graph( nodes = { @NODE( name = "I" ), @NODE( name = "you" ) }, relationships = { @REL( start = "I", end = "you", type = "know", properties = { @PROP( key = "since", value = "today" ) } ) }, autoIndexRelationships = true )
@Documented
@Title( "Items can not be added manually to a relationship AutoIndex" )
public void items_can_not_be_added_manually_to_a_Relationship_AutoIndex() throws Exception
{
data.get();
String indexName = graphdb().index()
.getRelationshipAutoIndexer()
.getAutoIndex()
.getName();
try ( Transaction tx = graphdb().beginTx() )
{
gen.get()
.noGraph()
.expectedStatus( 405 )
.payload( createJsonStringFor( getRelationshipUri( data.get()
.get( "I" )
.getRelationships()
.iterator()
.next() ), "name", "I" ) )
.post( postRelationshipIndexUri( indexName ) )
.entity();
}
}
/**
* It is not allowed to remove entries manually from automatic indexes.
*/
@Test
@Documented
@Graph( nodes = { @NODE( name = "I", setNameProperty = true ) }, autoIndexNodes = true )
@Title( "Automatically indexed nodes cannot be removed from the index manually" )
public void autoindexed_items_cannot_be_removed_manually()
{
long id = data.get()
.get( "I" )
.getId();
String indexName = graphdb().index()
.getNodeAutoIndexer()
.getAutoIndex()
.getName();
gen.get()
.noGraph()
.expectedStatus( 405 )
.delete( getDataUri() + "index/node/" + indexName + "/name/I/" + id )
.entity();
gen.get()
.noGraph()
.expectedStatus( 405 )
.delete( getDataUri() + "index/node/" + indexName + "/name/" + id )
.entity();
gen.get()
.noGraph()
.expectedStatus( 405 )
.delete( getDataUri() + "index/node/" + indexName + "/" + id )
.entity();
}
/**
* It is not allowed to remove entries manually from automatic indexes.
*/
@Test
@Documented
@Graph( nodes = { @NODE( name = "I" ), @NODE( name = "you" ) }, relationships = { @REL( start = "I", end = "you", type = "know", properties = { @PROP( key = "since", value = "today" ) } ) }, autoIndexRelationships = true )
@Title( "Automatically indexed relationships cannot be removed from the index manually" )
public void autoindexed_relationships_cannot_be_removed_manually()
{
try ( Transaction tx = graphdb().beginTx() )
{
long id = data.get()
.get( "I" )
.getRelationships()
.iterator()
.next()
.getId();
String indexName = graphdb().index()
.getRelationshipAutoIndexer()
.getAutoIndex()
.getName();
gen.get()
.noGraph()
.expectedStatus( 405 )
.delete( getDataUri() + "index/relationship/" + indexName + "/since/today/" + id )
.entity();
gen.get()
.noGraph()
.expectedStatus( 405 )
.delete( getDataUri() + "index/relationship/" + indexName + "/since/" + id )
.entity();
gen.get()
.noGraph()
.expectedStatus( 405 )
.delete( getDataUri() + "index/relationship/" + indexName + "/" + id )
.entity();
}
}
/**
* See the example request.
*/
@Documented
@Title( "Find relationship by query from an automatic index" )
@Test
@Graph( nodes = { @NODE( name = "I" ), @NODE( name = "you" ) }, relationships = { @REL( start = "I", end = "you", type = "know", properties = { @PROP( key = "since", value = "today" ) } ) }, autoIndexRelationships = true )
public void Find_relationship_by_query_from_an_automatic_index()
{
data.get();
assertSize( 1, gen.get()
.noGraph()
.expectedStatus( 200 )
.get( relationshipAutoIndexUri() + "?query=since:today" )
.entity() );
}
/**
* See the example request.
*/
@Documented
@Title( "Find relationship by exact match from an automatic index" )
@Test
@Graph( nodes = { @NODE( name = "I" ), @NODE( name = "you" ) }, relationships = { @REL( start = "I", end = "you", type = "know", properties = { @PROP( key = "since", value = "today" ) } ) }, autoIndexRelationships = true )
public void Find_relationship_by_exact_match_from_an_automatic_index()
{
data.get();
assertSize( 1, gen.get()
.noGraph()
.expectedStatus( 200 )
.get( relationshipAutoIndexUri() + "since/today/" )
.entity() );
}
/**
* Get current status for autoindexing on nodes.
*/
@Test
@Documented
public void getCurrentStatusForNodes() {
checkAndAssertAutoIndexerIsEnabled("node", false);
}
/**
* Enable node autoindexing.
*/
@Test
@Documented
public void enableNodeAutoIndexing() {
setEnabledAutoIndexingForType("node", true);
}
/**
* Add a property for autoindexing on nodes.
*/
@Test
@Documented
public void addAutoIndexingPropertyForNodes() {
gen.get()
.noGraph()
.expectedStatus( 204 )
.payload( "myProperty1" )
.post( autoIndexURI( "node" ) + "/properties" );
}
/**
* Lookup list of properties being autoindexed.
*/
@Test
@Documented
public void listAutoIndexingPropertiesForNodes() throws JsonParseException {
String propName = "some-property";
server().getDatabase().getGraph().index().getNodeAutoIndexer().startAutoIndexingProperty(propName);
List<String> properties = getAutoIndexedPropertiesForType("node");
assertEquals(1, properties.size());
assertEquals(propName, properties.get(0));
}
/**
* Remove a property for autoindexing on nodes.
*/
@Test
@Documented
public void removeAutoIndexingPropertyForNodes() {
gen.get()
.noGraph()
.expectedStatus( 204 )
.delete( autoIndexURI( "node" ) + "/properties/myProperty1" );
}
@Test
public void switchOnOffAutoIndexingForNodes() {
switchOnOffAutoIndexingForType("node");
}
@Test
public void switchOnOffAutoIndexingForRelationships() {
switchOnOffAutoIndexingForType("relationship");
}
@Test
public void addRemoveAutoIndexedPropertyForNodes() throws JsonParseException {
addRemoveAutoIndexedPropertyForType("node");
}
@Test
public void addRemoveAutoIndexedPropertyForRelationships() throws JsonParseException {
addRemoveAutoIndexedPropertyForType("relationship");
}
private String relationshipAutoIndexUri()
{
return getDataUri() + "index/auto/relationship/";
}
private void addRemoveAutoIndexedPropertyForType(String uriPartForType) throws JsonParseException {
// List<String> properties = getAutoIndexedPropertiesForType(uriPartForType);
// assertTrue(properties.isEmpty());
gen.get()
.noGraph()
.expectedStatus( 204 )
.payload( "myProperty1" )
.post(autoIndexURI(uriPartForType) + "/properties");
gen.get()
.noGraph()
.expectedStatus( 204 )
.payload( "myProperty2" )
.post(autoIndexURI(uriPartForType) + "/properties");
List<String> properties = getAutoIndexedPropertiesForType(uriPartForType);
assertEquals(2, properties.size());
assertTrue(properties.contains("myProperty1"));
assertTrue(properties.contains("myProperty2"));
gen.get()
.noGraph()
.expectedStatus(204)
.payload(null)
.delete(autoIndexURI(uriPartForType)
+ "/properties/myProperty2");
properties = getAutoIndexedPropertiesForType(uriPartForType);
assertEquals(1, properties.size());
assertTrue(properties.contains("myProperty1"));
}
@SuppressWarnings( "unchecked" )
private List<String> getAutoIndexedPropertiesForType(String uriPartForType)
throws JsonParseException
{
String result = gen.get()
.noGraph()
.expectedStatus( 200 )
.get(autoIndexURI(uriPartForType) + "/properties").entity();
return (List<String>) JsonHelper.readJson(result);
}
private void switchOnOffAutoIndexingForType(String uriPartForType)
{
setEnabledAutoIndexingForType(uriPartForType, true);
checkAndAssertAutoIndexerIsEnabled(uriPartForType, true);
setEnabledAutoIndexingForType(uriPartForType, false);
checkAndAssertAutoIndexerIsEnabled(uriPartForType, false);
}
private void setEnabledAutoIndexingForType(String uriPartForType,
boolean enabled)
{
gen.get()
.noGraph()
.expectedStatus( 204 )
.payload( Boolean.toString( enabled ) )
.put(autoIndexURI(uriPartForType) + "/status");
}
private void checkAndAssertAutoIndexerIsEnabled(String uriPartForType,
boolean enabled)
{
String result = gen.get()
.noGraph()
.expectedStatus( 200 )
.get(autoIndexURI(uriPartForType) + "/status").entity();
assertEquals(enabled, Boolean.parseBoolean(result));
}
private String autoIndexURI(String type)
{
return getDataUri()
+ RestfulGraphDatabase.PATH_AUTO_INDEX.replace("{type}", type);
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_AutoIndexDocIT.java
|
2,372
|
public class AbstractRestFunctionalTestBase extends SharedServerTestBase implements GraphHolder
{
protected static final String NODES = "http://localhost:7474/db/data/node/";
public @Rule
TestData<Map<String, Node>> data = TestData.producedThrough( GraphDescription.createGraphFor(
this, true ) );
public @Rule
TestData<RESTDocsGenerator> gen = TestData.producedThrough( RESTDocsGenerator.PRODUCER );
@Before
public void setUp()
{
gen().setSection( getDocumentationSectionName() );
}
@Before
public void cleanContent()
{
cleanDatabase();
gen().setGraph( graphdb() );
}
@SafeVarargs
public final String doCypherRestCall( String endpoint, String scriptTemplate, Status status,
Pair<String, String>... params )
{
String parameterString = createParameterString( params );
return doCypherRestCall( endpoint, scriptTemplate, status, parameterString );
}
public String doCypherRestCall( String endpoint, String scriptTemplate, Status status, String parameterString )
{
data.get();
String script = createScript( scriptTemplate );
String queryString = "{\"query\": \"" + script + "\",\"params\":{" + parameterString + "}}";
String snippet = org.neo4j.cypher.internal.compiler.v2_0.prettifier.Prettifier$.MODULE$.apply(script);
gen().expectedStatus( status.getStatusCode() )
.payload( queryString )
.description( AsciidocHelper.createAsciiDocSnippet( "cypher", snippet ) );
return gen().post( endpoint ).entity();
}
protected String formatJavaScript( String script )
{
script = script.replace( ";", "\n" );
if ( !script.endsWith( "\n" ) )
{
script += "\n";
}
return "_Raw script source_\n\n" + "[source, javascript]\n" + "----\n"
+ script + "----\n";
}
private Long idFor( String name )
{
return data.get().get( name ).getId();
}
private String createParameterString( Pair<String, String>[] params )
{
String paramString = "";
for ( Pair<String, String> param : params )
{
String delimiter = paramString.isEmpty() || paramString.endsWith( "{" ) ? "" : ",";
paramString += delimiter + "\"" + param.first() + "\":\"" + param.other() + "\"";
}
return paramString;
}
protected String createScript( String template )
{
for ( String key : data.get().keySet() )
{
template = template.replace( "%" + key + "%", idFor( key ).toString() );
}
return template;
}
protected String startGraph( String name )
{
return AsciidocHelper.createGraphVizWithNodeId( "Starting Graph", graphdb(), name );
}
@Override
public GraphDatabaseService graphdb()
{
return server().getDatabase().getGraph();
}
protected String getDataUri()
{
return "http://localhost:7474/db/data/";
}
protected String getDatabaseUri()
{
return "http://localhost:7474/db/";
}
protected String getNodeUri( Node node )
{
return getNodeUri(node.getId());
}
protected String getNodeUri( long node )
{
return getDataUri() + PATH_NODES + "/" + node;
}
protected String getRelationshipUri( Relationship relationship )
{
return getDataUri() + PATH_RELATIONSHIPS + "/" + relationship.getId();
}
protected String postNodeIndexUri( String indexName )
{
return getDataUri() + PATH_NODE_INDEX + "/" + indexName;
}
protected String postRelationshipIndexUri( String indexName )
{
return getDataUri() + PATH_RELATIONSHIP_INDEX + "/" + indexName;
}
protected Node getNode( String name )
{
return data.get().get( name );
}
protected Node[] getNodes( String... names )
{
Node[] nodes = {};
ArrayList<Node> result = new ArrayList<>();
for (String name : names)
{
result.add( getNode( name ) );
}
return result.toArray(nodes);
}
public void assertSize( int expectedSize, String entity )
{
Collection<?> hits;
try
{
hits = (Collection<?>) JsonHelper.jsonToSingleValue( entity );
assertEquals( expectedSize, hits.size() );
}
catch ( PropertyValueException e )
{
throw new RuntimeException( e );
}
}
public String getPropertiesUri( Relationship rel )
{
return getRelationshipUri(rel)+ "/properties";
}
public String getPropertiesUri( Node node )
{
return getNodeUri(node)+ "/properties";
}
public RESTDocsGenerator gen() {
return gen.get();
}
public void description( String description )
{
gen().description( description );
}
protected String getDocumentationSectionName() {
return "dev/rest-api";
}
public String getLabelsUri()
{
return format( "%slabels", getDataUri() );
}
public String getPropertyKeysUri()
{
return format( "%spropertykeys", getDataUri() );
}
public String getNodesWithLabelUri( String label )
{
return format( "%slabel/%s/nodes", getDataUri(), label );
}
public String getNodesWithLabelAndPropertyUri( String label, String property, Object value ) throws UnsupportedEncodingException
{
return format( "%slabel/%s/nodes?%s=%s", getDataUri(), label, property, encode( createJsonFrom( value ), "UTF-8" ) );
}
public String getSchemaIndexUri()
{
return getDataUri() + PATH_SCHEMA_INDEX;
}
public String getSchemaIndexLabelUri( String label )
{
return getDataUri() + PATH_SCHEMA_INDEX + "/" + label;
}
public String getSchemaIndexLabelPropertyUri( String label, String property )
{
return getDataUri() + PATH_SCHEMA_INDEX + "/" + label + "/" + property;
}
public String getSchemaConstraintUri()
{
return getDataUri() + PATH_SCHEMA_CONSTRAINT;
}
public String getSchemaConstraintLabelUri( String label )
{
return getDataUri() + PATH_SCHEMA_CONSTRAINT + "/" + label;
}
public String getSchemaConstraintLabelUniquenessUri( String label )
{
return getDataUri() + PATH_SCHEMA_CONSTRAINT + "/" + label + "/uniqueness/";
}
public String getSchemaConstraintLabelUniquenessPropertyUri( String label, String property )
{
return getDataUri() + PATH_SCHEMA_CONSTRAINT + "/" + label + "/uniqueness/" + property;
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_AbstractRestFunctionalTestBase.java
|
2,373
|
{
@Override
protected Representation underlyingObjectToObject( Object object )
{
return itemConverter.convert( object );
}
} );
| false
|
community_server_src_main_java_org_neo4j_server_plugins_ResultConverter.java
|
2,374
|
{
@Override
Representation convert( Object obj )
{
return ValueRepresentation.number( ( (Number) obj ).intValue() );
}
}, CHAR_RESULT = new ValueResult( RepresentationType.CHAR )
| false
|
community_server_src_main_java_org_neo4j_server_plugins_ResultConverter.java
|
2,375
|
{
@Override
Node convert( GraphDatabaseAPI graphDb, Object value )
throws BadInputException
{
return convertNode( graphDb, value );
}
@Override
Node[] newArray( int size )
{
return new Node[size];
}
} );
| false
|
community_server-api_src_main_java_org_neo4j_server_plugins_ParameterList.java
|
2,376
|
public class PluginLookupException extends Exception
{
PluginLookupException( String message )
{
super( message );
}
}
| false
|
community_server-api_src_main_java_org_neo4j_server_plugins_PluginLookupException.java
|
2,377
|
public final class PluginInvocationFailureException extends Exception
{
PluginInvocationFailureException( Throwable cause )
{
super( cause );
}
}
| false
|
community_server-api_src_main_java_org_neo4j_server_plugins_PluginInvocationFailureException.java
|
2,378
|
matches()
{
@Override
boolean match( String pattern, String string )
{
return string.matches( pattern );
}
},
| false
|
community_server-plugin-test_src_test_java_org_neo4j_server_plugins_PluginFunctionalTestHelper.java
|
2,379
|
end( "ends with" )
{
@Override
boolean match( String pattern, String string )
{
return string.endsWith( pattern );
}
},
| false
|
community_server-plugin-test_src_test_java_org_neo4j_server_plugins_PluginFunctionalTestHelper.java
|
2,380
|
public static class RegExp extends TypeSafeMatcher<String>
{
enum MatchType
{
end( "ends with" )
{
@Override
boolean match( String pattern, String string )
{
return string.endsWith( pattern );
}
},
matches()
{
@Override
boolean match( String pattern, String string )
{
return string.matches( pattern );
}
},
;
private final String description;
abstract boolean match( String pattern, String string );
private MatchType()
{
this.description = name();
}
private MatchType( String description )
{
this.description = description;
}
}
private final String pattern;
private String string;
private final MatchType type;
RegExp( String regexp, MatchType type )
{
this.pattern = regexp;
this.type = type;
}
@Factory
public static Matcher<String> endsWith( String pattern )
{
return new RegExp( pattern, MatchType.end );
}
@Override
public boolean matchesSafely( String string )
{
this.string = string;
return type.match( pattern, string );
}
@Override
public void describeTo( Description descr )
{
descr.appendText( "expected something that " )
.appendText( type.description )
.appendText( " [" )
.appendText( pattern )
.appendText( "] but got [" )
.appendText( string )
.appendText( "]" );
}
}
| false
|
community_server-plugin-test_src_test_java_org_neo4j_server_plugins_PluginFunctionalTestHelper.java
|
2,381
|
public class PluginFunctionalTestHelper
{
public static Map<String, Object> makeGet( String url ) throws JsonParseException {
JaxRsResponse response = new RestRequest().get(url);
String body = getResponseText(response);
response.close();
return deserializeMap(body);
}
protected static Map<String, Object> deserializeMap( final String body ) throws JsonParseException
{
Map<String, Object> result = JsonHelper.jsonToMap( body );
assertThat( result, CoreMatchers.is( not( nullValue() ) ) );
return result;
}
private static List<Map<String, Object>> deserializeList( final String body ) throws JsonParseException
{
List<Map<String, Object>> result = JsonHelper.jsonToList( body );
assertThat( result, CoreMatchers.is( not( nullValue() ) ) );
return result;
}
protected static String getResponseText( final JaxRsResponse response )
{
String body = response.getEntity();
Assert.assertEquals( body, 200, response.getStatus() );
return body;
}
protected static Map<String, Object> makePostMap( String url ) throws JsonParseException
{
JaxRsResponse response = new RestRequest().post(url,null);
String body = getResponseText( response );
response.close();
return deserializeMap( body );
}
protected static Map<String, Object> makePostMap( String url, Map<String, Object> params )
throws JsonParseException
{
String json = JsonHelper.createJsonFrom( params );
JaxRsResponse response = new RestRequest().post(url, json, MediaType.APPLICATION_JSON_TYPE);
String body = getResponseText( response );
response.close();
return deserializeMap( body );
}
protected static List<Map<String, Object>> makePostList( String url ) throws JsonParseException {
JaxRsResponse response = new RestRequest().post(url, null);
String body = getResponseText(response);
response.close();
return deserializeList(body);
}
protected static List<Map<String, Object>> makePostList( String url, Map<String, Object> params )
throws JsonParseException {
String json = JsonHelper.createJsonFrom(params);
JaxRsResponse response = new RestRequest().post(url, json);
String body = getResponseText(response);
response.close();
return deserializeList(body);
}
public static class RegExp extends TypeSafeMatcher<String>
{
enum MatchType
{
end( "ends with" )
{
@Override
boolean match( String pattern, String string )
{
return string.endsWith( pattern );
}
},
matches()
{
@Override
boolean match( String pattern, String string )
{
return string.matches( pattern );
}
},
;
private final String description;
abstract boolean match( String pattern, String string );
private MatchType()
{
this.description = name();
}
private MatchType( String description )
{
this.description = description;
}
}
private final String pattern;
private String string;
private final MatchType type;
RegExp( String regexp, MatchType type )
{
this.pattern = regexp;
this.type = type;
}
@Factory
public static Matcher<String> endsWith( String pattern )
{
return new RegExp( pattern, MatchType.end );
}
@Override
public boolean matchesSafely( String string )
{
this.string = string;
return type.match( pattern, string );
}
@Override
public void describeTo( Description descr )
{
descr.appendText( "expected something that " )
.appendText( type.description )
.appendText( " [" )
.appendText( pattern )
.appendText( "] but got [" )
.appendText( string )
.appendText( "]" );
}
}
}
| false
|
community_server-plugin-test_src_test_java_org_neo4j_server_plugins_PluginFunctionalTestHelper.java
|
2,382
|
@SuppressWarnings( "unchecked" )
public class PluginFunctionalTest extends SharedServerTestBase
{
private static FunctionalTestHelper functionalTestHelper;
@BeforeClass
public static void setupServer() throws IOException
{
functionalTestHelper = new FunctionalTestHelper( SharedServerTestBase.server() );
}
@Before
public void cleanTheDatabase()
{
ServerHelper.cleanTheDatabase( SharedServerTestBase.server() );
}
@Test
public void canGetGraphDatabaseExtensionList() throws Exception
{
Map<String, Object> map = PluginFunctionalTestHelper.makeGet( functionalTestHelper.dataUri() );
assertThat( map.get( "extensions" ), instanceOf( Map.class ) );
}
@Test
public void canGetExtensionDefinitionForReferenceNodeExtension() throws Exception
{
Map<String, Object> map = PluginFunctionalTestHelper.makeGet( functionalTestHelper.dataUri() );
map = (Map<String, Object>) map.get( "extensions" );
assertThat( map.get( FunctionalTestPlugin.class.getSimpleName() ), instanceOf( Map.class ) );
}
@Test
public void canGetExtensionDataForCreateNode() throws Exception
{
Map<String, Object> map = PluginFunctionalTestHelper.makeGet( functionalTestHelper.dataUri() );
map = (Map<String, Object>) map.get( "extensions" );
map = (Map<String, Object>) map.get( FunctionalTestPlugin.class.getSimpleName() );
assertThat( (String) map.get( FunctionalTestPlugin.CREATE_NODE ), RegExp.endsWith( String.format(
"/ext/%s/graphdb/%s", FunctionalTestPlugin.class.getSimpleName(),
FunctionalTestPlugin.CREATE_NODE ) ) );
}
@Test
public void canGetExtensionDescription() throws Exception
{
Map<String, Object> map = PluginFunctionalTestHelper.makeGet( functionalTestHelper.dataUri() );
map = (Map<String, Object>) map.get( "extensions" );
map = (Map<String, Object>) map.get( FunctionalTestPlugin.class.getSimpleName() );
String uri = (String) map.get( FunctionalTestPlugin.CREATE_NODE );
PluginFunctionalTestHelper.makeGet( uri );
}
@Test
public void canInvokeExtensionMethodWithNoArguments() throws Exception
{
Map<String, Object> map = PluginFunctionalTestHelper.makeGet( functionalTestHelper.dataUri() );
map = (Map<String, Object>) map.get( "extensions" );
map = (Map<String, Object>) map.get( FunctionalTestPlugin.class.getSimpleName() );
String uri = (String) map.get( FunctionalTestPlugin.CREATE_NODE );
Map<String, Object> description = PluginFunctionalTestHelper.makePostMap( uri );
NodeRepresentationTest.verifySerialisation( description );
}
@Test
public void canInvokeNodePlugin() throws Exception
{
long n = functionalTestHelper.getGraphDbHelper()
.createNode();
Map<String, Object> map = PluginFunctionalTestHelper.makeGet( functionalTestHelper.nodeUri( n ) );
map = (Map<String, Object>) map.get( "extensions" );
map = (Map<String, Object>) map.get( FunctionalTestPlugin.class.getSimpleName() );
String uri = (String) map.get( FunctionalTestPlugin.GET_CONNECTED_NODES );
List<Map<String, Object>> response = PluginFunctionalTestHelper.makePostList( uri );
verifyNodes( response );
}
private void verifyNodes( final List<Map<String, Object>> response )
{
for ( Map<String, Object> nodeMap : response )
{
NodeRepresentationTest.verifySerialisation( nodeMap );
}
}
@Test
public void canInvokePluginWithParam() throws Exception
{
long n = functionalTestHelper.getGraphDbHelper()
.createNode();
Map<String, Object> map = PluginFunctionalTestHelper.makeGet( functionalTestHelper.dataUri() );
map = (Map<String, Object>) map.get( "extensions" );
map = (Map<String, Object>) map.get( FunctionalTestPlugin.class.getSimpleName() );
String uri = (String) map.get( "methodWithIntParam" );
Map<String, Object> params = MapUtil.map( "id", n );
Map<String, Object> node = PluginFunctionalTestHelper.makePostMap( uri, params );
NodeRepresentationTest.verifySerialisation( node );
}
@Test
public void canInvokePluginOnRelationship() throws Exception
{
long n1 = functionalTestHelper.getGraphDbHelper()
.createNode();
long n2 = functionalTestHelper.getGraphDbHelper()
.createNode();
long relId = functionalTestHelper.getGraphDbHelper()
.createRelationship( "pals", n1, n2 );
String uri = getPluginMethodUri( functionalTestHelper.relationshipUri( relId ), "methodOnRelationship" );
Map<String, Object> params = MapUtil.map( "id", relId );
List<Map<String, Object>> nodes = PluginFunctionalTestHelper.makePostList( uri, params );
verifyNodes( nodes );
}
private String getPluginMethodUri( String startUrl, String methodName ) throws JsonParseException
{
Map<String, Object> map = PluginFunctionalTestHelper.makeGet( startUrl );
map = (Map<String, Object>) map.get( "extensions" );
map = (Map<String, Object>) map.get( FunctionalTestPlugin.class.getSimpleName() );
return (String) map.get( methodName );
}
@Test
public void shouldBeAbleToInvokePluginWithLotsOfParams() throws Exception
{
String methodUri = getPluginMethodUri( functionalTestHelper.dataUri(), "methodWithAllParams" );
String a = "a";
byte b = (byte) 0xff;
char c = 'c';
short d = (short) 4;
int e = 365;
long f = (long) 4;
float g = (float) 4.5;
double h = Math.PI;
boolean i = false;
Map<String, Object> params = MapUtil.map( "id", a, "id2", b, "id3", c, "id4", d, "id5", e, "id6", f, "id7", g,
"id8", h, "id9", i );
PluginFunctionalTestHelper.makePostMap( methodUri, params );
assertThat( FunctionalTestPlugin._string, is( a ) );
assertThat( FunctionalTestPlugin._byte, is( b ) );
assertThat( FunctionalTestPlugin._character, is( c ) );
assertThat( FunctionalTestPlugin._short, is( d ) );
assertThat( FunctionalTestPlugin._integer, is( e ) );
assertThat( FunctionalTestPlugin._long, is( f ) );
assertThat( FunctionalTestPlugin._float, is( g ) );
assertThat( FunctionalTestPlugin._double, is( h ) );
assertThat( FunctionalTestPlugin._boolean, is( i ) );
}
@Test
public void shouldHandleOptionalValuesCorrectly1() throws Exception
{
long n = functionalTestHelper.getGraphDbHelper()
.createNode();
String methodUri = getPluginMethodUri( functionalTestHelper.nodeUri( n ), "getThisNodeOrById" );
Map<String, Object> map = PluginFunctionalTestHelper.makePostMap( methodUri );
NodeRepresentationTest.verifySerialisation( map );
}
@Test
public void shouldHandleOptionalValuesCorrectly2() throws Exception
{
long n = functionalTestHelper.getGraphDbHelper()
.createNode();
String methodUri = getPluginMethodUri( functionalTestHelper.nodeUri( n ), "getThisNodeOrById" );
long id = functionalTestHelper.getGraphDbHelper()
.getFirstNode();
Map<String, Object> params = MapUtil.map( "id", id );
PluginFunctionalTestHelper.makePostMap( methodUri, params );
assertThat( FunctionalTestPlugin.optional, is( id ) );
}
@Test
public void canInvokePluginWithNodeParam() throws Exception
{
long n = functionalTestHelper.getGraphDbHelper()
.createNode();
long m = functionalTestHelper.getGraphDbHelper()
.createNode();
functionalTestHelper.getGraphDbHelper()
.createRelationship( "LOVES", n, m );
functionalTestHelper.getGraphDbHelper()
.createRelationship( "LOVES", m, n );
functionalTestHelper.getGraphDbHelper()
.createRelationship( "KNOWS", m, functionalTestHelper.getGraphDbHelper()
.createNode() );
functionalTestHelper.getGraphDbHelper()
.createRelationship( "KNOWS", n, functionalTestHelper.getGraphDbHelper()
.createNode() );
Map<String, Object> map = PluginFunctionalTestHelper.makeGet( functionalTestHelper.nodeUri( n ) );
map = (Map<String, Object>) map.get( "extensions" );
map = (Map<String, Object>) map.get( FunctionalTestPlugin.class.getSimpleName() );
String uri = (String) map.get( "getRelationshipsBetween" );
List<Map<String, Object>> response = PluginFunctionalTestHelper.makePostList( uri,
MapUtil.map( "other", functionalTestHelper.nodeUri( m ) ) );
assertEquals( 2, response.size() );
verifyRelationships( response );
}
@Test
public void canInvokePluginWithNodeListParam() throws Exception
{
long n = functionalTestHelper.getGraphDbHelper()
.createNode();
Map<String, Object> map = PluginFunctionalTestHelper.makeGet( functionalTestHelper.nodeUri( n ) );
map = (Map<String, Object>) map.get( "extensions" );
map = (Map<String, Object>) map.get( FunctionalTestPlugin.class.getSimpleName() );
List<String> nodes = Arrays.asList( functionalTestHelper.nodeUri( functionalTestHelper.getGraphDbHelper()
.createNode() ), functionalTestHelper.nodeUri( functionalTestHelper.getGraphDbHelper()
.createNode() ), functionalTestHelper.nodeUri( functionalTestHelper.getGraphDbHelper()
.createNode() ) );
String uri = (String) map.get( "createRelationships" );
List<Map<String, Object>> response = PluginFunctionalTestHelper.makePostList( uri,
MapUtil.map( "type", "KNOWS", "nodes", nodes ) );
assertEquals( nodes.size(), response.size() );
verifyRelationships( response );
}
private void verifyRelationships( final List<Map<String, Object>> response )
{
for ( Map<String, Object> relMap : response )
{
RelationshipRepresentationTest.verifySerialisation( relMap );
}
}
@Test
public void shouldHandleSets() throws Exception
{
String methodUri = getPluginMethodUri( functionalTestHelper.dataUri(), "methodWithSet" );
List<String> strings = Arrays.asList( "aaa", "bbb", "aaa" );
Map<String, Object> params = MapUtil.map( "strings", strings );
PluginFunctionalTestHelper.makePostMap( methodUri, params );
Set<String> stringsSet = new HashSet<>( strings );
assertThat( FunctionalTestPlugin.stringSet, is( stringsSet ) );
}
@Test
public void shouldHandleJsonLists() throws Exception
{
String methodUri = getPluginMethodUri( functionalTestHelper.dataUri(), "methodWithList" );
List<String> strings = Arrays.asList( "aaa", "bbb", "aaa" );
Map<String, Object> params = MapUtil.map( "strings", strings );
PluginFunctionalTestHelper.makePostMap( methodUri, params );
List<String> stringsList = new ArrayList<>( strings );
assertThat( FunctionalTestPlugin.stringList, is( stringsList ) );
}
@Test
public void shouldHandleUrlEncodedLists() throws Exception
{
String methodUri = getPluginMethodUri( functionalTestHelper.dataUri(), "methodWithList" );
String postBody = "strings[]=aaa&strings[]=bbb&strings[]=ccc";
RestRequest.req().post( methodUri ,postBody,MediaType.APPLICATION_FORM_URLENCODED_TYPE);
List<String> strings = Arrays.asList( "aaa", "bbb", "ccc" );
List<String> stringsList = new ArrayList<>( strings );
assertThat( FunctionalTestPlugin.stringList, is( stringsList ) );
}
@Test
public void shouldHandleUrlEncodedListsAndInt() throws Exception
{
String methodUri = getPluginMethodUri( functionalTestHelper.dataUri(), "methodWithListAndInt" );
String postBody = "strings[]=aaa&strings[]=bbb&strings[]=ccc&count=3";
RestRequest.req().post(methodUri,postBody,MediaType.APPLICATION_FORM_URLENCODED_TYPE);
List<String> strings = Arrays.asList( "aaa", "bbb", "ccc" );
List<String> stringsList = new ArrayList<>( strings );
assertThat( FunctionalTestPlugin.stringList, is( stringsList ) );
assertThat( FunctionalTestPlugin._integer, is( 3 ) );
}
@Test
public void shouldHandleArrays() throws Exception
{
String methodUri = getPluginMethodUri( functionalTestHelper.dataUri(), "methodWithArray" );
String[] stringArray = { "aaa", "bbb", "aaa" };
List<String> strings = Arrays.asList( stringArray );
Map<String, Object> params = MapUtil.map( "strings", strings );
PluginFunctionalTestHelper.makePostMap( methodUri, params );
assertThat( FunctionalTestPlugin.stringArray, is( stringArray ) );
}
@Test
public void shouldHandlePrimitiveArrays() throws Exception
{
String methodUri = getPluginMethodUri( functionalTestHelper.dataUri(), "methodWithIntArray" );
Integer[] intArray = { 5, 6, 7, 8 };
List<Integer> ints = Arrays.asList( intArray );
Map<String, Object> params = MapUtil.map( "ints", ints );
PluginFunctionalTestHelper.makePostMap( methodUri, params );
assertThat( FunctionalTestPlugin.intArray, is( new int[] { 5, 6, 7, 8 } ) );
}
@Test
public void shouldHandleOptionalArrays() throws Exception
{
String methodUri = getPluginMethodUri( functionalTestHelper.dataUri(), "methodWithOptionalArray" );
PluginFunctionalTestHelper.makePostMap( methodUri );
assertThat( FunctionalTestPlugin.intArray, is( nullValue() ) );
}
@Test
public void shouldBeAbleToReturnPaths() throws Exception
{
long n = functionalTestHelper.getGraphDbHelper()
.createNode();
long r = functionalTestHelper.getGraphDbHelper()
.getFirstNode();
functionalTestHelper.getGraphDbHelper()
.createRelationship( "friend", n, r );
String methodUri = getPluginMethodUri( functionalTestHelper.nodeUri( n ), "pathToReference" );
Map<String, Object> maps = PluginFunctionalTestHelper.makePostMap( methodUri );
assertThat( (String) maps.get( "start" ), endsWith( Long.toString( r ) ) );
assertThat( (String) maps.get( "end" ), endsWith( Long.toString( n ) ) );
}
@Test
public void shouldHandleNullPath() throws Exception {
long n = functionalTestHelper.getGraphDbHelper()
.createNode();
String url = getPluginMethodUri(functionalTestHelper.nodeUri(n), "pathToReference");
JaxRsResponse response = new RestRequest().post(url, null);
assertThat( response.getEntity(), response.getStatus(), is(204) );
response.close();
}
}
| false
|
community_server-plugin-test_src_test_java_org_neo4j_server_plugins_PluginFunctionalTest.java
|
2,383
|
{
@Override
public boolean accept( Relationship item )
{
return item.getOtherNode( start )
.equals( end );
}
} );
| false
|
community_server-plugin-test_src_test_java_org_neo4j_server_plugins_Plugin.java
|
2,384
|
@Description( "Here you can describe your plugin. It will show up in the description of the methods." )
public class Plugin extends ServerPlugin
{
public static final String GET_CONNECTED_NODES = "connected_nodes";
static String _string;
static Byte _byte;
static Character _character;
static Integer _integer;
static Short _short;
static Long _long;
static Float _float;
static Double _double;
static Boolean _boolean;
static Long optional;
static Set<String> stringSet;
static List<String> stringList;
static String[] stringArray;
public static int[] intArray;
@Name( GET_CONNECTED_NODES )
@PluginTarget( Node.class )
public Iterable<Node> getAllConnectedNodes( @Source Node start )
{
ArrayList<Node> nodes = new ArrayList<Node>();
for ( Relationship rel : start.getRelationships() )
{
nodes.add( rel.getOtherNode( start ) );
}
return nodes;
}
@PluginTarget( Node.class )
public Iterable<Relationship> getRelationshipsBetween( final @Source Node start,
final @Parameter( name = "other" ) Node end )
{
return new FilteringIterable<>( start.getRelationships(), new Predicate<Relationship>()
{
@Override
public boolean accept( Relationship item )
{
return item.getOtherNode( start )
.equals( end );
}
} );
}
@PluginTarget( Node.class )
public Iterable<Relationship> createRelationships( @Source Node start,
@Parameter( name = "type" ) RelationshipType type, @Parameter( name = "nodes" ) Iterable<Node> nodes )
{
List<Relationship> result = new ArrayList<>();
try(Transaction tx = start.getGraphDatabase().beginTx())
{
for ( Node end : nodes )
{
result.add( start.createRelationshipTo( end, type ) );
}
tx.success();
}
return result;
}
@PluginTarget( Node.class )
public Node getThisNodeOrById( @Source Node start, @Parameter( name = "id", optional = true ) Long id )
{
optional = id;
if ( id == null )
{
return start;
}
return start.getGraphDatabase()
.getNodeById( id );
}
@PluginTarget( GraphDatabaseService.class )
public Node methodWithIntParam( @Source GraphDatabaseService db, @Parameter( name = "id", optional = false ) int id )
{
return db.getNodeById( id );
}
@PluginTarget( Relationship.class )
public Iterable<Node> methodOnRelationship( @Source Relationship rel )
{
return Arrays.asList( rel.getNodes() );
}
@PluginTarget( GraphDatabaseService.class )
public Node methodWithAllParams( @Source GraphDatabaseService db,
@Parameter( name = "id", optional = false ) String a, @Parameter( name = "id2", optional = false ) Byte b,
@Parameter( name = "id3", optional = false ) Character c,
@Parameter( name = "id4", optional = false ) Short d,
@Parameter( name = "id5", optional = false ) Integer e,
@Parameter( name = "id6", optional = false ) Long f, @Parameter( name = "id7", optional = false ) Float g,
@Parameter( name = "id8", optional = false ) Double h,
@Parameter( name = "id9", optional = false ) Boolean i )
{
_string = a;
_byte = b;
_character = c;
_short = d;
_integer = e;
_long = f;
_float = g;
_double = h;
_boolean = i;
return db.createNode();
}
@PluginTarget( GraphDatabaseService.class )
public Node methodWithSet( @Source GraphDatabaseService db,
@Parameter( name = "strings", optional = false ) Set<String> params )
{
stringSet = params;
return db.createNode();
}
@PluginTarget( GraphDatabaseService.class )
public Node methodWithList( @Source GraphDatabaseService db,
@Parameter( name = "strings", optional = false ) List<String> params )
{
stringList = params;
return db.createNode();
}
@PluginTarget( GraphDatabaseService.class )
public Node methodWithArray( @Source GraphDatabaseService db,
@Parameter( name = "strings", optional = false ) String[] params )
{
stringArray = params;
return db.createNode();
}
@PluginTarget( GraphDatabaseService.class )
public Node methodWithIntArray( @Source GraphDatabaseService db,
@Parameter( name = "ints", optional = false ) int[] params )
{
intArray = params;
return db.createNode();
}
@PluginTarget( GraphDatabaseService.class )
public Node methodWithOptionalArray( @Source GraphDatabaseService db,
@Parameter( name = "ints", optional = true ) int[] params )
{
intArray = params;
return db.createNode();
}
@PluginTarget( Node.class )
public Path pathToReference( @Source Node me )
{
PathFinder<Path> finder = GraphAlgoFactory.shortestPath( Traversal.expanderForAllTypes(), 6 );
return finder.findSinglePath( me.getGraphDatabase()
.createNode(), me );
}
}
| false
|
community_server-plugin-test_src_test_java_org_neo4j_server_plugins_Plugin.java
|
2,385
|
private static abstract class Converter<T>
{
abstract T convert( GraphDatabaseAPI graphDb, Object value )
throws BadInputException;
abstract T[] newArray( int size );
}
| false
|
community_server-api_src_main_java_org_neo4j_server_plugins_ParameterList.java
|
2,386
|
{
@Override
Double convert( GraphDatabaseAPI graphDb, Object value )
throws BadInputException
{
return convertDouble( value );
}
@Override
Double[] newArray( int size )
{
return new Double[size];
}
} );
| false
|
community_server-api_src_main_java_org_neo4j_server_plugins_ParameterList.java
|
2,387
|
{
@Override
Float convert( GraphDatabaseAPI graphDb, Object value )
throws BadInputException
{
return convertFloat( value );
}
@Override
Float[] newArray( int size )
{
return new Float[size];
}
} );
| false
|
community_server-api_src_main_java_org_neo4j_server_plugins_ParameterList.java
|
2,388
|
{
@Override
Short convert( GraphDatabaseAPI graphDb, Object value )
throws BadInputException
{
return convertShort( value );
}
@Override
Short[] newArray( int size )
{
return new Short[size];
}
} );
| false
|
community_server-api_src_main_java_org_neo4j_server_plugins_ParameterList.java
|
2,389
|
{
@Override
Boolean convert( GraphDatabaseAPI graphDb, Object value )
throws BadInputException
{
return convertBoolean( value );
}
@Override
Boolean[] newArray( int size )
{
return new Boolean[size];
}
} );
| false
|
community_server-api_src_main_java_org_neo4j_server_plugins_ParameterList.java
|
2,390
|
{
@Override
Character convert( GraphDatabaseAPI graphDb, Object value )
throws BadInputException
{
return convertCharacter( value );
}
@Override
Character[] newArray( int size )
{
return new Character[size];
}
} );
| false
|
community_server-api_src_main_java_org_neo4j_server_plugins_ParameterList.java
|
2,391
|
{
@Override
Byte convert( GraphDatabaseAPI graphDb, Object value )
throws BadInputException
{
return convertByte( value );
}
@Override
Byte[] newArray( int size )
{
return new Byte[size];
}
} );
| false
|
community_server-api_src_main_java_org_neo4j_server_plugins_ParameterList.java
|
2,392
|
{
@Override
Long convert( GraphDatabaseAPI graphDb, Object value )
throws BadInputException
{
return convertLong( value );
}
@Override
Long[] newArray( int size )
{
return new Long[size];
}
} );
| false
|
community_server-api_src_main_java_org_neo4j_server_plugins_ParameterList.java
|
2,393
|
{
@Override
Integer convert( GraphDatabaseAPI graphDb, Object value )
throws BadInputException
{
return convertInteger( value );
}
@Override
Integer[] newArray( int size )
{
return new Integer[size];
}
} );
| false
|
community_server-api_src_main_java_org_neo4j_server_plugins_ParameterList.java
|
2,394
|
{
@Override
URI convert( GraphDatabaseAPI graphDb, Object value )
throws BadInputException
{
return convertURI( value );
}
@Override
URI[] newArray( int size )
{
return new URI[size];
}
} );
| false
|
community_server-api_src_main_java_org_neo4j_server_plugins_ParameterList.java
|
2,395
|
{
@Override
Relationship convert( GraphDatabaseAPI graphDb, Object value )
throws BadInputException
{
return convertRelationship( graphDb, value );
}
@Override
Relationship[] newArray( int size )
{
return new Relationship[size];
}
} );
| false
|
community_server-api_src_main_java_org_neo4j_server_plugins_ParameterList.java
|
2,396
|
@Provider
public class PluginInvocatorProvider extends InjectableProvider<PluginInvocator>
{
private final AbstractNeoServer neoServer;
public PluginInvocatorProvider( AbstractNeoServer neoServer )
{
super( PluginInvocator.class );
this.neoServer = neoServer;
}
@Override
public PluginInvocator getValue( HttpContext c )
{
return neoServer.getExtensionManager();
}
}
| false
|
community_server_src_main_java_org_neo4j_server_plugins_PluginInvocatorProvider.java
|
2,397
|
public final class PluginManager implements ExtensionInjector, PluginInvocator
{
private final Map<String/*name*/, ServerExtender> extensions = new HashMap<String, ServerExtender>();
public PluginManager( Configuration serverConfig, Logging logging )
{
this( serverConfig, ServerPlugin.load(), logging );
}
PluginManager( Configuration serverConfig, Iterable<ServerPlugin> plugins, Logging logging )
{
Map<String, Pair<ServerPlugin, ServerExtender>> extensions = new HashMap<String, Pair<ServerPlugin, ServerExtender>>();
ConsoleLogger log = logging.getConsoleLog( getClass() );
for ( ServerPlugin plugin : plugins )
{
PluginPointFactory factory = new PluginPointFactoryImpl();
final ServerExtender extender = new ServerExtender( factory );
try
{
plugin.loadServerExtender( extender );
}
catch ( Exception ex )
{
log.warn( "Failed to load plugin [%s]: %s", plugin.toString(), ex.getMessage() );
continue;
}
catch ( LinkageError err )
{
log.warn( "Failed to load plugin [%s]: %s", plugin.toString(), err.getMessage() );
continue;
}
Pair<ServerPlugin, ServerExtender> old = extensions.put( plugin.name, Pair.of( plugin, extender ) );
if ( old != null )
{
log.warn( String.format( "Extension naming conflict \"%s\" between \"%s\" and \"%s\"", plugin.name,
old.first().getClass(), plugin.getClass() ) );
}
}
for ( Pair<ServerPlugin, ServerExtender> extension : extensions.values() )
{
log.log( String.format( "Loaded server plugin \"%s\"", extension.first().name ) );
for ( PluginPoint point : extension.other().all() )
{
log.log( String.format( " %s.%s: %s", point.forType().getSimpleName(), point.name(),
point.getDescription() ) );
}
this.extensions.put( extension.first().name, extension.other() );
}
}
@Override
public Map<String, List<String>> getExensionsFor( Class<?> type )
{
Map<String, List<String>> result = new HashMap<String, List<String>>();
for ( Map.Entry<String, ServerExtender> extension : extensions.entrySet() )
{
List<String> methods = new ArrayList<String>();
for ( PluginPoint method : extension.getValue()
.getExtensionsFor( type ) )
{
methods.add( method.name() );
}
if ( !methods.isEmpty() )
{
result.put( extension.getKey(), methods );
}
}
return result;
}
private PluginPoint extension( String name, Class<?> type, String method ) throws PluginLookupException
{
ServerExtender extender = extensions.get( name );
if ( extender == null )
{
throw new PluginLookupException( "No such ServerPlugin: \"" + name + "\"" );
}
return extender.getExtensionPoint( type, method );
}
@Override
public ExtensionPointRepresentation describe( String name, Class<?> type, String method )
throws PluginLookupException
{
return describe( extension( name, type, method ) );
}
private ExtensionPointRepresentation describe( PluginPoint extension )
{
ExtensionPointRepresentation representation = new ExtensionPointRepresentation( extension.name(),
extension.forType(), extension.getDescription() );
extension.describeParameters( representation );
return representation;
}
@Override
public List<ExtensionPointRepresentation> describeAll( String name ) throws PluginLookupException
{
ServerExtender extender = extensions.get( name );
if ( extender == null )
{
throw new PluginLookupException( "No such ServerPlugin: \"" + name + "\"" );
}
List<ExtensionPointRepresentation> result = new ArrayList<ExtensionPointRepresentation>();
for ( PluginPoint plugin : extender.all() )
{
result.add( describe( plugin ) );
}
return result;
}
@Override
public <T> Representation invoke( GraphDatabaseAPI graphDb, String name, Class<T> type, String method,
T context, ParameterList params ) throws PluginLookupException, BadInputException,
PluginInvocationFailureException, BadPluginInvocationException
{
PluginPoint plugin = extension( name, type, method );
try
{
return plugin.invoke( graphDb, context, params );
}
catch ( BadInputException e )
{
throw e;
}
catch ( BadPluginInvocationException e )
{
throw e;
}
catch ( PluginInvocationFailureException e )
{
throw e;
}
catch ( Exception e )
{
throw new PluginInvocationFailureException( e );
}
}
@Override
public Set<String> extensionNames()
{
return Collections.unmodifiableSet( extensions.keySet() );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_plugins_PluginManager.java
|
2,398
|
{
@Override
@SuppressWarnings( "boxing" )
Representation convert( Object obj )
{
return ValueRepresentation.bool( (Boolean) obj );
}
}, INT_RESULT = new ValueResult( RepresentationType.INTEGER )
| false
|
community_server_src_main_java_org_neo4j_server_plugins_ResultConverter.java
|
2,399
|
public class PluginManagerTest
{
private static PluginManager manager;
private static GraphDatabaseAPI graphDb;
@BeforeClass
public static void loadExtensionManager() throws Exception
{
graphDb = (GraphDatabaseAPI) new TestGraphDatabaseFactory().newImpermanentDatabase();
manager = new PluginManager( null, DevNullLoggingService.DEV_NULL );
}
@AfterClass
public static void destroyExtensionManager()
{
manager = null;
if ( graphDb != null )
{
graphDb.shutdown();
}
graphDb = null;
}
@Test
public void canGetUrisForNode() throws Exception
{
Map<String, List<String>> extensions = manager.getExensionsFor( GraphDatabaseService.class );
List<String> methods = extensions.get( FunctionalTestPlugin.class.getSimpleName() );
assertNotNull( methods );
assertThat( methods, hasItem( FunctionalTestPlugin.CREATE_NODE ) );
}
@Test
public void canInvokeExtension() throws Exception
{
manager.invoke( graphDb, FunctionalTestPlugin.class.getSimpleName(), GraphDatabaseService.class,
FunctionalTestPlugin.CREATE_NODE, graphDb,
new NullFormat( null, (MediaType[]) null ).readParameterList( "" ) );
}
}
| false
|
community_server-plugin-test_src_test_java_org_neo4j_server_plugins_PluginManagerTest.java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.