Unnamed: 0
int64 0
6.7k
| func
stringlengths 12
89.6k
| target
bool 2
classes | project
stringlengths 45
151
|
|---|---|---|---|
1,800
|
public class WebDriverFacade
{
private WebDriver browser;
public WebDriver getWebDriver() throws InvocationTargetException, IllegalAccessException, InstantiationException
{
if ( browser == null )
{
String driverName = lookupDriverImplementation();
try
{
browser = WebDriverImplementation.valueOf( driverName ).createInstance();
}
catch ( Exception problem )
{
throw new RuntimeException( "Couldn't instantiate the selected selenium driver. See nested exception.", problem );
}
}
return browser;
}
private String lookupDriverImplementation()
{
String driverName = System.getProperty( "webdriver.implementation", WebDriverImplementation.Firefox.name() );
System.out.println( "Using " + driverName );
return driverName;
}
public enum WebDriverImplementation {
Firefox()
{
public WebDriver createInstance()
{
return new FirefoxDriver();
}
},
Chrome() {
public WebDriver createInstance()
{
WebdriverChromeDriver.ensurePresent();
return new ChromeDriver();
}
},
SauceLabsFirefoxWindows() {
public WebDriver createInstance() throws MalformedURLException
{
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability( "version", "5" );
capabilities.setCapability( "platform", Platform.VISTA );
capabilities.setCapability( "name", "Neo4j Web Testing" );
return WebdriverSauceLabsDriver.createDriver( capabilities );
}
},
SauceLabsChromeWindows() {
public WebDriver createInstance() throws MalformedURLException
{
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability( "platform", Platform.VISTA );
capabilities.setCapability( "name", "Neo4j Web Testing" );
return WebdriverSauceLabsDriver.createDriver( capabilities );
}
},
SauceLabsInternetExplorerWindows() {
public WebDriver createInstance() throws MalformedURLException
{
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability( "platform", Platform.VISTA );
capabilities.setCapability( "name", "Neo4j Web Testing" );
return WebdriverSauceLabsDriver.createDriver( capabilities );
}
};
public abstract WebDriver createInstance() throws Exception;
}
public void quitBrowser() throws IllegalAccessException, InvocationTargetException, InstantiationException
{
if ( browser != null )
{
browser.quit();
}
}
}
| false
|
community_server_src_webtest_java_org_neo4j_server_webdriver_WebDriverFacade.java
|
1,801
|
public class JmxAttributeRepresentation extends ObjectRepresentation
{
protected ObjectName objectName;
protected MBeanAttributeInfo attrInfo;
protected MBeanServer jmxServer = ManagementFactory.getPlatformMBeanServer();
private static final RepresentationDispatcher REPRESENTATION_DISPATCHER = new JmxAttributeRepresentationDispatcher();
public JmxAttributeRepresentation( ObjectName objectName, MBeanAttributeInfo attrInfo )
{
super( "jmxAttribute" );
this.objectName = objectName;
this.attrInfo = attrInfo;
}
@Mapping( "name" )
public ValueRepresentation getName()
{
return ValueRepresentation.string( attrInfo.getName() );
}
@Mapping( "description" )
public ValueRepresentation getDescription()
{
return ValueRepresentation.string( attrInfo.getDescription() );
}
@Mapping( "type" )
public ValueRepresentation getType()
{
return ValueRepresentation.string( attrInfo.getType() );
}
@Mapping( "isReadable" )
public ValueRepresentation isReadable()
{
return bool( attrInfo.isReadable() );
}
@Mapping( "isWriteable" )
public ValueRepresentation isWriteable()
{
return bool( attrInfo.isWritable() );
}
@Mapping( "isIs" )
public ValueRepresentation isIs()
{
return bool( attrInfo.isIs() );
}
private ValueRepresentation bool( Boolean value )
{
return ValueRepresentation.string( value ? "true" : "false " );
}
@Mapping( "value" )
public Representation getValue()
{
try
{
Object value = jmxServer.getAttribute( objectName, attrInfo.getName() );
return REPRESENTATION_DISPATCHER.dispatch( value, "" );
}
catch ( Exception e )
{
return ValueRepresentation.string( "N/A" );
}
}
}
| false
|
community_server_src_main_java_org_neo4j_server_webadmin_rest_representations_JmxAttributeRepresentation.java
|
1,802
|
Firefox()
{
public WebDriver createInstance()
{
return new FirefoxDriver();
}
},
| false
|
community_server_src_webtest_java_org_neo4j_server_webdriver_WebDriverFacade.java
|
1,803
|
public class DocOutput implements Output, Serializable
{
private static final long serialVersionUID = 1L;
private final ByteArrayOutputStream baos = new ByteArrayOutputStream();
private final PrintWriter out = new PrintWriter( baos );
@Override
public Appendable append( final CharSequence csq, final int start, final int end )
throws IOException
{
this.print( RemoteOutput.asString( csq ).substring( start, end ) );
return this;
}
@Override
public Appendable append( final char c ) throws IOException
{
this.print( c );
return this;
}
@Override
public Appendable append( final CharSequence csq ) throws IOException
{
this.print( RemoteOutput.asString( csq ) );
return this;
}
@Override
public void println( final Serializable object ) throws RemoteException
{
out.println( object );
out.flush();
}
@Override
public void println() throws RemoteException
{
out.println();
out.flush();
}
@Override
public void print( final Serializable object ) throws RemoteException
{
out.print( object );
out.flush();
}
}
| false
|
community_shell_src_test_java_org_neo4j_shell_Documenter.java
|
1,804
|
public class Documenter
{
public class DocOutput implements Output, Serializable
{
private static final long serialVersionUID = 1L;
private final ByteArrayOutputStream baos = new ByteArrayOutputStream();
private final PrintWriter out = new PrintWriter( baos );
@Override
public Appendable append( final CharSequence csq, final int start, final int end )
throws IOException
{
this.print( RemoteOutput.asString( csq ).substring( start, end ) );
return this;
}
@Override
public Appendable append( final char c ) throws IOException
{
this.print( c );
return this;
}
@Override
public Appendable append( final CharSequence csq ) throws IOException
{
this.print( RemoteOutput.asString( csq ) );
return this;
}
@Override
public void println( final Serializable object ) throws RemoteException
{
out.println( object );
out.flush();
}
@Override
public void println() throws RemoteException
{
out.println();
out.flush();
}
@Override
public void print( final Serializable object ) throws RemoteException
{
out.print( object );
out.flush();
}
}
public class Job
{
public final String query;
public final String assertion;
public final String comment;
public Job( final String query, final String assertion, final String comment )
{
this.query = query;
this.assertion = assertion;
this.comment = comment;
}
}
private final String title;
private final Stack<Job> stack = new Stack<Documenter.Job>();
private final ShellClient client;
public Documenter( final String title, final ShellServer server )
{
this.title = title;
try
{
this.client = new SameJvmClient( new HashMap<String, Serializable>(), server,
new CollectingOutput() );
}
catch ( Exception e )
{
throw Exceptions.launderedException( "Error creating client",e );
}
}
public void add( final String query, final String assertion, final String comment )
{
stack.push( new Job( query, assertion, comment ) );
}
public void run()
{
PrintWriter out = getWriter( this.title );
out.println();
out.println( "[source, bash]" );
out.println( "-----" );
for ( Job job : stack )
{
try
{
DocOutput output = new DocOutput();
String prompt = client.getPrompt();
client.evaluate( job.query, output );
String result = output.baos.toString();
assertTrue( result + "did not contain " + job.assertion, result.contains( job.assertion ) );
doc( job, out, result, prompt );
}
catch ( ShellException e )
{
throw new RuntimeException( e );
}
}
out.println( "-----" );
out.flush();
out.close();
}
PrintWriter getWriter( String title )
{
return AsciiDocGenerator.getPrintWriter( "target/docs/dev/shell", title );
}
private void doc( final Job job, final PrintWriter out, final String result, String prompt )
{
if ( job.query != null && !job.query.isEmpty() )
{
out.println( " # " + job.comment );
out.println( " " + prompt + job.query );
if ( result != null && !result.isEmpty() )
{
out.println( " " + result.replace( "\n", "\n " ) );
}
out.println();
}
}
}
| false
|
community_shell_src_test_java_org_neo4j_shell_Documenter.java
|
1,805
|
private static class RawColumn extends Column
{
public RawColumn( int indentation )
{
super( multiply( " ", indentation ) );
}
@Override
boolean print( Output out, int i ) throws RemoteException
{
String value = cells.get( i );
if ( value.length() > 0 )
{
for ( String line : value.split( lineSeparator() ) )
{
out.print( prefix + "|" + line + lineSeparator() );
}
return true;
}
return false;
}
}
| false
|
community_shell_src_main_java_org_neo4j_shell_ColumnPrinter.java
|
1,806
|
private static class Column
{
private int widest = 0;
protected final List<String> cells = new ArrayList<String>();
protected final String prefix;
public Column( String prefix )
{
this.prefix = prefix;
}
void add( String cell )
{
cells.add( cell );
widest = Math.max( widest, cell.length() );
}
int size()
{
return cells.size();
}
boolean print( Output out, int i ) throws RemoteException
{
String value = cells.get( i );
out.print( prefix + value + multiply( " ", widest - value.length() + 1 ) );
return value.length() > 0;
}
}
| false
|
community_shell_src_main_java_org_neo4j_shell_ColumnPrinter.java
|
1,807
|
public class ColumnPrinter
{
private final Column rawColumn;
private final List<Column> columns = new ArrayList<Column>();
public ColumnPrinter( String... columnPrefixes )
{
for ( String prefix : columnPrefixes )
{
this.columns.add( new Column( prefix ) );
}
rawColumn = new RawColumn( columnPrefixes[0].length() );
}
public void add( Object... columns )
{
Iterator<Column> columnIterator = this.columns.iterator();
rawColumn.add( "" );
for ( Object column : columns )
{
columnIterator.next().add( column.toString() );
}
if ( columnIterator.hasNext() )
{
throw new IllegalArgumentException( "Invalid column count " + columns.length + ", expected " +
this.columns.size() );
}
}
public void addRaw( String string )
{
rawColumn.add( string );
for ( Column col : columns )
{
col.add( "" );
}
}
public void print( Output out ) throws RemoteException
{
Column firstColumn = columns.get( 0 );
for ( int line = 0; line < firstColumn.size(); line++ )
{
if ( !rawColumn.print( out, line ) )
{
firstColumn.print( out, line );
for ( int col = 1; col < columns.size(); col++ )
{
columns.get( col ).print( out, line );
}
}
out.println();
}
}
private static class Column
{
private int widest = 0;
protected final List<String> cells = new ArrayList<String>();
protected final String prefix;
public Column( String prefix )
{
this.prefix = prefix;
}
void add( String cell )
{
cells.add( cell );
widest = Math.max( widest, cell.length() );
}
int size()
{
return cells.size();
}
boolean print( Output out, int i ) throws RemoteException
{
String value = cells.get( i );
out.print( prefix + value + multiply( " ", widest - value.length() + 1 ) );
return value.length() > 0;
}
}
private static class RawColumn extends Column
{
public RawColumn( int indentation )
{
super( multiply( " ", indentation ) );
}
@Override
boolean print( Output out, int i ) throws RemoteException
{
String value = cells.get( i );
if ( value.length() > 0 )
{
for ( String line : value.split( lineSeparator() ) )
{
out.print( prefix + "|" + line + lineSeparator() );
}
return true;
}
return false;
}
}
private static String multiply( String string, int count )
{
StringBuilder builder = new StringBuilder();
for ( int i = 0; i < count; i++ )
{
builder.append( string );
}
return builder.toString();
}
}
| false
|
community_shell_src_main_java_org_neo4j_shell_ColumnPrinter.java
|
1,808
|
public class BigLabelStoreGenerator
{
private static Random random = new Random();
public static void main(String[] args)
{
long batchSize = parseLong( withDefault( System.getenv().get( "BATCH_SIZE" ), "100000" ) );
long numNodes = parseLong( withDefault( System.getenv( "NUM_NODES" ), "1000000" ) );
int numLabels = parseInt( withDefault( System.getenv( "NUM_LABELS" ), "5" ) );
String graphDbPath = System.getenv( "GRAPH_DB" );
System.out.println( format( "# BATCH_SIZE: %d, NUM_NODES: %d, NUM_LABELS: %d, GRAPH_DB: '%s'",
batchSize, numNodes, numLabels, graphDbPath ) );
GraphDatabaseService graph = createGraphDatabaseService( graphDbPath );
Label[] labels = createLabels( numLabels );
int[] statistics = new int[numLabels];
assert( numLabels == labels.length );
long labelings = 0;
long start = System.currentTimeMillis();
try {
for ( long l = 0; l < numNodes; l += batchSize )
{
long batchStart = System.currentTimeMillis();
try ( Transaction tx = graph.beginTx() )
{
for ( long m = 0; m < batchSize; m++ )
{
Label[] selectedLabels = pickRandomLabels( labels );
for (int i = 0; i < selectedLabels.length; i++)
{
statistics[i]++;
}
labelings += selectedLabels.length;
graph.createNode( selectedLabels );
}
tx.success();
}
long batchDuration = System.currentTimeMillis() - batchStart;
System.out.println( format( "nodes: %d, ratio: %d, labelings: %d, duration: %d, label statistics: %s",
l, l*100/numNodes, labelings, batchDuration, Arrays.toString( statistics ) ) );
}
}
finally
{
graph.shutdown();
}
long duration = System.currentTimeMillis() - start;
System.out.println( format( "nodes: %d, ratio: %d, labelings: %d, duration: %d", numNodes, 100, labelings, duration ) );
}
private static GraphDatabaseService createGraphDatabaseService( String graphDbPath )
{
GraphDatabaseFactory factory = new GraphDatabaseFactory();
GraphDatabaseBuilder graphBuilder = factory.newEmbeddedDatabaseBuilder( graphDbPath );
File propertiesFile = new File( graphDbPath, "neo4j.properties");
if ( propertiesFile.exists() && propertiesFile.isFile() && propertiesFile.canRead() )
{
System.out.println( format( "# Loading properties file '%s'", propertiesFile.getAbsolutePath() ) );
graphBuilder.loadPropertiesFromFile( propertiesFile.getAbsolutePath() );
}
else
{
System.out.println( format( "# No properties file found at '%s'", propertiesFile.getAbsolutePath() ) );
}
return graphBuilder.newGraphDatabase();
}
private static String withDefault( String value, String defaultValue )
{
return null == value ? defaultValue : value;
}
private static Label[] pickRandomLabels( Label[] labels )
{
return Arrays.copyOf( labels, 1 + random.nextInt( labels.length ) );
}
private static Label[] createLabels( int numLabels )
{
Label[] labels = new DynamicLabel[numLabels];
for ( int i = 0; i < numLabels; i++ )
{
labels[i] = DynamicLabel.label( format( "LABEL_%d", i ) );
}
return labels;
}
}
| false
|
community_shell_src_main_java_org_neo4j_shell_BigLabelStoreGenerator.java
|
1,809
|
public class AppCommandParser
{
private final AppShellServer server;
private final String line;
private String appName;
private App app;
private final Map<String, String> options = new HashMap<>();
private final List<String> arguments = new ArrayList<>();
/**
* @param server the server used to find apps.
* @param line the line from the client to interpret.
* @throws Exception if there's something wrong with the line.
*/
public AppCommandParser( AppShellServer server, String line )
throws Exception
{
this.server = server;
this.line = line;
String trimmedLine = line != null ? prepareLine( line ) : line;
this.parse( trimmedLine );
}
private String prepareLine( String line )
{
// Replace \n with space, and remove comments
line = line.trim();
String[] lines = line.split( "\n" );
StringBuilder builder = new StringBuilder();
for ( String singleLine : lines )
{
if ( singleLine.startsWith( "//" ) )
{
continue; // Skip comments
}
if ( builder.length() > 0 )
{
builder.append( ' ' );
}
builder.append( singleLine );
}
return builder.toString();
}
private void parse( String line ) throws Exception
{
if ( line == null || line.trim().length() == 0 )
{
app = new NoopApp();
return;
}
this.parseApp( line );
this.parseParameters( line );
}
/**
* Extracts the app name (f.ex. ls or rm) from the supplied line.
*
* @param line the line to extract the app name from.
* @return the app name for {@code line}.
*/
public static String parseOutAppName( String line )
{
int index = findNextWhiteSpace( line, 0 );
return index == -1 ? line : line.substring( 0, index );
}
private void parseApp( String line ) throws Exception
{
int index = findNextWhiteSpace( line, 0 );
appName = index == -1 ? line : line.substring( 0, index );
appName = appName.toLowerCase();
app = server.findApp( appName );
if ( app == null )
{
throw new ShellException( "Unknown command '" + appName + "'" );
}
}
private void parseParameters( String line ) throws ShellException
{
String rest = line.substring( appName.length() ).trim();
String[] parsed = tokenizeStringWithQuotes( rest, false );
for ( int i = 0; i < parsed.length; i++ )
{
String string = parsed[i];
if ( app.takesOptions() && isMultiCharOption( string ) )
{
String name = string.substring( 2 );
i = fetchArguments( parsed, i, name );
}
else if ( app.takesOptions() && isSingleCharOption( string ) )
{
String options = string.substring( 1 );
for ( int o = 0; o < options.length(); o++ )
{
String name = String.valueOf( options.charAt( o ) );
i = fetchArguments( parsed, i, name );
}
}
else if ( string.length() > 0 )
{
this.arguments.add( string );
}
}
}
private boolean isOption( String string )
{
return isSingleCharOption( string ) || isMultiCharOption( string );
}
private boolean isMultiCharOption( String string )
{
return string.startsWith( "--" );
}
private boolean isSingleCharOption( String string )
{
return string.startsWith( "-" ) && !isANegativeNumber( string );
}
private boolean isANegativeNumber( String string )
{
try
{
Integer.parseInt( string );
return true;
}
catch ( NumberFormatException e )
{
return false;
}
}
private int fetchArguments( String[] parsed, int whereAreWe, String optionName ) throws ShellException
{
String value = null;
OptionDefinition definition =
this.app.getOptionDefinition( optionName );
if ( definition == null )
{
throw new ShellException( "Unrecognized option '" + optionName + "'" );
}
OptionValueType type = definition.getType();
if ( type == OptionValueType.MUST )
{
whereAreWe++;
String message = "Value required for '" + optionName + "'";
this.assertHasIndex( parsed, whereAreWe, message );
value = parsed[whereAreWe];
if ( this.isOption( value ) )
{
throw new ShellException( message );
}
}
else if ( type == OptionValueType.MAY )
{
if ( this.hasIndex( parsed, whereAreWe + 1 ) &&
!this.isOption( parsed[whereAreWe + 1] ) )
{
whereAreWe++;
value = parsed[whereAreWe];
}
}
this.options.put( optionName, value );
return whereAreWe;
}
private boolean hasIndex( String[] array, int index )
{
return index >= 0 && index < array.length;
}
private void assertHasIndex( String[] array, int index, String message ) throws ShellException
{
if ( !this.hasIndex( array, index ) )
{
throw new ShellException( message );
}
}
private static int findNextWhiteSpace( String line, int fromIndex )
{
int index = line.indexOf( ' ', fromIndex );
return index == -1 ? line.indexOf( '\t', fromIndex ) : index;
}
/** @return the name of the app (from {@link #getLine()}). */
public String getAppName()
{
return this.appName;
}
/** @return the app corresponding to the {@link #getAppName()}. */
public App app()
{
return this.app;
}
/** @return the supplied options (from {@link #getLine()}). */
public Map<String, String> options()
{
return this.options;
}
public String option( String name, String defaultValue )
{
String result = options.get( name );
return result != null ? result : defaultValue;
}
public Number optionAsNumber( String name, Number defaultValue )
{
String value = option( name, null );
if ( value != null )
{
if ( value.indexOf( ',' ) != -1 || value.indexOf( '.' ) != -1 )
{
return Double.valueOf( value );
}
else
{
return Integer.valueOf( value );
}
}
return defaultValue;
}
/** @return the arguments (from {@link #getLine()}). */
public List<String> arguments()
{
return this.arguments;
}
public String argumentWithDefault( int index, String defaultValue )
{
return index < arguments.size() ? arguments.get( index ) : defaultValue;
}
public String argument( int index, String errorMessageIfItDoesNotExist ) throws ShellException
{
if ( index >= arguments.size() )
{
throw new ShellException( errorMessageIfItDoesNotExist );
}
return arguments.get( index );
}
/** @return the entire line from the client. */
public String getLine()
{
return this.line;
}
/** @return the line w/o the app (just the options and arguments). */
public String getLineWithoutApp()
{
return this.line.substring( this.appName.length() ).trim();
}
}
| false
|
community_shell_src_main_java_org_neo4j_shell_AppCommandParser.java
|
1,810
|
public abstract class AbstractShellTest
{
protected GraphDatabaseAPI db;
protected ShellServer shellServer;
private ShellClient shellClient;
private Integer remotelyAvailableOnPort;
protected static final RelationshipType RELATIONSHIP_TYPE = withName( "TYPE" );
@Rule
public EphemeralFileSystemRule fs = new EphemeralFileSystemRule();
private Transaction tx;
@Before
public void doBefore() throws Exception
{
db = newDb();
shellServer = newServer( db );
shellClient = newShellClient( shellServer );
}
protected SameJvmClient newShellClient( ShellServer server ) throws ShellException, RemoteException
{
return newShellClient( server, Collections.<String, Serializable>singletonMap( "quiet", true ) );
}
protected SameJvmClient newShellClient( ShellServer server, Map<String, Serializable> session )
throws ShellException, RemoteException
{
return new SameJvmClient( session, server, new CollectingOutput() );
}
protected GraphDatabaseAPI newDb()
{
return (GraphDatabaseAPI) new TestGraphDatabaseFactory().setFileSystem( fs.get() ).newImpermanentDatabase();
}
protected ShellServer newServer( GraphDatabaseAPI db ) throws ShellException, RemoteException
{
return new GraphDatabaseShellServer( db );
}
@After
public void doAfter() throws Exception
{
if ( tx != null )
{
finishTx( false );
}
shellClient.shutdown();
shellServer.shutdown();
db.shutdown();
}
protected void beginTx()
{
assert tx == null;
tx = db.beginTx();
}
protected void finishTx()
{
finishTx( true );
}
protected ShellClient newRemoteClient() throws Exception
{
return newRemoteClient( NO_INITIAL_SESSION );
}
protected ShellClient newRemoteClient( Map<String, Serializable> initialSession ) throws Exception
{
return new RemoteClient( initialSession, remoteLocation( remotelyAvailableOnPort ),
new CollectingOutput() );
}
protected void makeServerRemotelyAvailable() throws RemoteException
{
if ( remotelyAvailableOnPort == null )
{
remotelyAvailableOnPort = findFreePort();
shellServer.makeRemotelyAvailable( remotelyAvailableOnPort, SimpleAppServer.DEFAULT_NAME );
}
}
private int findFreePort()
{
// TODO
return SimpleAppServer.DEFAULT_PORT;
}
protected void restartServer() throws Exception
{
shellServer.shutdown();
db.shutdown();
db = newDb();
remotelyAvailableOnPort = null;
shellServer = newServer( db );
shellClient = newShellClient( shellServer );
}
protected void finishTx( boolean success )
{
assert tx != null;
if ( success )
tx.success();
tx.finish();
tx = null;
}
protected static String pwdOutputFor( Object... entities )
{
StringBuilder builder = new StringBuilder();
for ( Object entity : entities )
{
builder.append( (builder.length() == 0 ? "" : "-->") );
if ( entity instanceof Node )
{
builder.append( "(" ).append( ((Node) entity).getId() ).append( ")" );
}
else
{
builder.append( "<" ).append( ((Relationship) entity).getId() ).append( ">" );
}
}
return Pattern.quote( builder.toString() );
}
public void executeCommand( String command, String... theseLinesMustExistRegEx ) throws Exception
{
executeCommand( shellClient, command, theseLinesMustExistRegEx );
}
public void executeCommand( ShellClient client, String command,
String... theseLinesMustExistRegEx ) throws Exception
{
CollectingOutput output = new CollectingOutput();
client.evaluate( command, output );
for ( String lineThatMustExist : theseLinesMustExistRegEx )
{
boolean negative = lineThatMustExist.startsWith( "!" );
lineThatMustExist = negative ? lineThatMustExist.substring( 1 ) : lineThatMustExist;
Pattern pattern = compile( lineThatMustExist );
boolean found = false;
for ( String line : output )
{
if ( pattern.matcher( line ).find() )
{
found = true;
break;
}
}
assertTrue( "Was expecting a line matching '" + lineThatMustExist + "', but didn't find any from out of " +
asCollection( output ), found != negative );
}
}
public void executeCommandExpectingException( String command, String errorMessageShouldContain ) throws Exception
{
CollectingOutput output = new CollectingOutput();
try
{
shellClient.evaluate( command, output );
fail( "Was expecting an exception" );
}
catch ( ShellException e )
{
String errorMessage = e.getMessage();
if ( !errorMessage.toLowerCase().contains( errorMessageShouldContain.toLowerCase() ) )
{
fail( "Error message '" + errorMessage + "' should have contained '" + errorMessageShouldContain + "'" );
}
}
}
protected void assertRelationshipDoesntExist( Relationship relationship )
{
assertRelationshipDoesntExist( relationship.getId() );
}
protected void assertRelationshipDoesntExist( long id )
{
try ( Transaction ignore = db.beginTx() )
{
db.getRelationshipById( id );
fail( "Relationship " + id + " shouldn't exist" );
}
catch ( NotFoundException e )
{
// Good
}
}
protected void assertNodeExists( Node node )
{
assertNodeExists( node.getId() );
}
protected void assertNodeExists( long id )
{
try ( Transaction ignore = db.beginTx() )
{
db.getNodeById( id );
}
catch ( NotFoundException e )
{
fail( "Node " + id + " should exist" );
}
}
protected void assertNodeDoesntExist( Node node )
{
assertNodeDoesntExist( node.getId() );
}
protected void assertNodeDoesntExist( long id )
{
try ( Transaction ignore = db.beginTx() )
{
db.getNodeById( id );
fail( "Relationship " + id + " shouldn't exist" );
}
catch ( NotFoundException e )
{
// Good
}
}
protected Relationship[] createRelationshipChain( int length )
{
return createRelationshipChain( RELATIONSHIP_TYPE, length );
}
protected Relationship[] createRelationshipChain( RelationshipType type, int length )
{
try( Transaction transaction = db.beginTx() )
{
Relationship[] relationshipChain = createRelationshipChain( db.createNode(), type, length );
transaction.success();
return relationshipChain;
}
}
protected Relationship[] createRelationshipChain( Node startingFromNode, RelationshipType type,
int length )
{
try ( Transaction tx = db.beginTx() )
{
Relationship[] rels = new Relationship[length];
Node firstNode = startingFromNode;
for ( int i = 0; i < rels.length; i++ )
{
Node secondNode = db.createNode();
rels[i] = firstNode.createRelationshipTo( secondNode, type );
firstNode = secondNode;
}
tx.success();
return rels;
}
}
protected void deleteRelationship( Relationship relationship )
{
try ( Transaction tx = db.beginTx() )
{
relationship.delete();
tx.success();
}
}
protected void setProperty( Node node, String key, Object value )
{
try ( Transaction tx = db.beginTx() )
{
node.setProperty( key, value );
tx.success();
}
}
protected Node getCurrentNode() throws RemoteException, ShellException
{
Serializable current = shellServer.interpretVariable( shellClient.getId(), Variables.CURRENT_KEY );
int nodeId = parseInt( current.toString().substring( 1 ) );
try ( Transaction tx = db.beginTx() )
{
Node nodeById = db.getNodeById( nodeId );
tx.success();
return nodeById;
}
}
}
| false
|
community_shell_src_test_java_org_neo4j_shell_AbstractShellTest.java
|
1,811
|
public class WebdriverSauceLabsDriver
{
public static final String WEBDRIVER_SAUCE_LABS_URL = "webdriver.sauce.labs.url";
public static WebDriver createDriver( DesiredCapabilities capabilities ) throws MalformedURLException
{
String sauceLabsUrl = System.getProperty( WEBDRIVER_SAUCE_LABS_URL );
if (sauceLabsUrl == null)
{
throw new IllegalArgumentException( String.format( "To use SauceLabs, %s system property must be provided",
WEBDRIVER_SAUCE_LABS_URL) );
}
WebDriver driver = new RemoteWebDriver(
new URL( sauceLabsUrl ),
capabilities);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
return driver;
}
}
| false
|
community_server_src_webtest_java_org_neo4j_server_webdriver_WebdriverSauceLabsDriver.java
|
1,812
|
static class ElementClickable extends BaseMatcher<ElementReference>
{
public boolean matches( Object item )
{
try {
((ElementReference) item).click();
return true;
}
catch ( WebDriverException webDriverException )
{
if (webDriverException.getMessage().contains( "Element is not clickable" ))
{
return false;
} else {
throw webDriverException;
}
}
}
public void describeTo( Description description )
{
description.appendText( "Should be clickable" );
}
}
| false
|
community_server_src_webtest_java_org_neo4j_server_webdriver_WebdriverLibrary.java
|
1,813
|
public class WebdriverLibrary
{
protected final WebDriver d;
public WebdriverLibrary(WebDriverFacade df) throws InvocationTargetException, IllegalAccessException, InstantiationException {
d = df.getWebDriver();
}
public WebDriver getWebDriver() {
return d;
}
public void clickOn(String contains) {
clickOnByXpath("//*[contains(.,'"+contains+"')]");
}
public void clickOn(By by) {
getElement( by ).click();
}
public void clickOnButton(String text) {
clickOnByXpath("//div[contains(.,'"+text+"') and contains(@class, 'button')]");
}
public void clickOnLink(String text) {
clickOnByXpath( "//a[contains(.,'"+text+"')]");
}
public void clickOnByXpath( String xpath )
{
clickOn( By.xpath( xpath ) );
}
public void waitForUrlToBe(String url) {
waitUntil( browserUrlIs( url ), "Url did not change to expected value within a reasonable time." );
}
public void waitForTitleToBe(String title) {
waitUntil( browserTitleIs( title ), "Title did not change to expected value within a reasonable time." );
}
public void waitForElementToAppear(By by) {
waitUntil( elementVisible( by ), "Element ("+by.toString()+") did not appear within a reasonable time." );
}
public void waitForElementToDisappear(By by) {
waitUntil( not( elementVisible( by )), "Element did not disappear within a reasonable time." );
}
public void clearInput(ElementReference el) {
int len = el.getValue().length();
CharSequence[] backspaces = new CharSequence[len];
Arrays.fill(backspaces, Keys.BACK_SPACE);
el.sendKeys( backspaces );
}
public void waitUntil(Matcher<WebDriver> matcher, String errorMessage) {
waitUntil( matcher, errorMessage, 10000);
}
public void waitUntil(Matcher<WebDriver> matcher, String errorMessage, long timeout) {
try {
Condition<WebDriver> cond = new WebdriverCondition<WebDriver>( getWebDriver(), matcher, d);
cond.waitUntilFulfilled(timeout, errorMessage);
} catch( TimeoutException e) {
fail(errorMessage);
}
}
public ElementReference getElement(By by) {
return new ElementReference(this, by);
}
public WebElement getWebElement(By by) {
waitForElementToAppear(by);
return d.findElement( by );
}
public void refresh() {
d.get( d.getCurrentUrl() );
}
static class ElementClickable extends BaseMatcher<ElementReference>
{
public boolean matches( Object item )
{
try {
((ElementReference) item).click();
return true;
}
catch ( WebDriverException webDriverException )
{
if (webDriverException.getMessage().contains( "Element is not clickable" ))
{
return false;
} else {
throw webDriverException;
}
}
}
public void describeTo( Description description )
{
description.appendText( "Should be clickable" );
}
}
}
| false
|
community_server_src_webtest_java_org_neo4j_server_webdriver_WebdriverLibrary.java
|
1,814
|
public class WebdriverConditionTimeoutException extends ConditionTimeoutException
{
/**
*
*/
private static final long serialVersionUID = 1L;
private String htmlDump;
public WebdriverConditionTimeoutException( String msg, String htmlDump, Throwable cause )
{
super( msg, cause );
this.htmlDump = htmlDump;
}
public String getHtmlDump() {
return htmlDump;
}
}
| false
|
community_server_src_webtest_java_org_neo4j_server_webdriver_WebdriverConditionTimeoutException.java
|
1,815
|
public class WebdriverCondition<T> extends Condition<T>
{
private final WebDriver d;
public WebdriverCondition( WebDriver d, Matcher<T> matcher, T state )
{
super( matcher, state );
this.d = d;
}
public void waitUntilFulfilled(long timeout, String errorMessage) {
try {
super.waitUntilFulfilled( timeout, errorMessage );
} catch(WebdriverConditionTimeoutException e) {
throw e;
} catch(Exception e) {
e.printStackTrace();
throw new WebdriverConditionTimeoutException("Webdriver condition failed ("+ e.getMessage() +"), see nested exception. HTML dump follows:\n\n" + d.getPageSource() + "\n\n", d.getPageSource(), e);
}
}
}
| false
|
community_server_src_webtest_java_org_neo4j_server_webdriver_WebdriverCondition.java
|
1,816
|
public class WebdriverChromeDriver
{
public static final String WEBDRIVER_CHROME_DRIVER = "webdriver.chrome.driver";
public static final String WEBDRIVER_CHROME_DRIVER_DOWNLOAD_URL = "webdriver.chrome.driver.download.url";
public static void ensurePresent()
{
String chromeDriverPath = System.getProperty( WEBDRIVER_CHROME_DRIVER );
if (chromeDriverPath == null) {
throw new IllegalArgumentException( String.format("Please specify system property %s " +
"pointing to the location where you expect the chrome driver binary to be present",
WEBDRIVER_CHROME_DRIVER) );
}
if (new File( chromeDriverPath ).exists()) {
System.out.println( "Chrome driver found at " + chromeDriverPath );
return;
}
String chromeDriverDownloadUrl = System.getProperty( WEBDRIVER_CHROME_DRIVER_DOWNLOAD_URL );
if (chromeDriverDownloadUrl ==null) {
throw new IllegalArgumentException( String.format( "No file present at %s=\"%s\", " +
"please specify system property %s for where to fetch it from",
WEBDRIVER_CHROME_DRIVER, chromeDriverPath, WEBDRIVER_CHROME_DRIVER_DOWNLOAD_URL ) );
}
ZipFile zipFile = downloadFile( chromeDriverDownloadUrl );
extractTo( zipFile, chromeDriverPath );
}
private static ZipFile downloadFile( String fromUrl )
{
System.out.println("Downloading binary from " + fromUrl);
try
{
URL zipUrl = new URL( fromUrl );
ReadableByteChannel rbc = Channels.newChannel( zipUrl.openStream() );
File localPath = new File( System.getProperty( "java.io.tmpdir" ), "chromedriver.zip" );
FileOutputStream zipOutputStream = new FileOutputStream( localPath );
zipOutputStream.getChannel().transferFrom(rbc, 0, 1 << 24);
return new ZipFile( localPath );
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
}
private static void extractTo( ZipFile zipFile, String destination )
{
System.out.println("Extracting binary to " + destination);
try
{
new File( destination ).getParentFile().mkdirs();
Enumeration<? extends ZipEntry> entries = zipFile.entries();
InputStream inputStream = zipFile.getInputStream( entries.nextElement() );
OutputStream outputStream = new BufferedOutputStream( new FileOutputStream( destination ) );
IOUtils.copy( inputStream, outputStream );
inputStream.close();
outputStream.close();
if (entries.hasMoreElements())
{
throw new IllegalStateException( "Unexpected additional entries in zip file" );
}
new File( destination ).setExecutable( true );
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
}
}
| false
|
community_server_src_webtest_java_org_neo4j_server_webdriver_WebdriverChromeDriver.java
|
1,817
|
public class WebadminWebdriverLibrary extends WebdriverLibrary
{
private static final String USE_DEV_HTML_FILE_KEY = "testWithDevHtmlFile";
private static final String AVOID_REDIRECT_AND_GO_STRAIGHT_TO_WEB_ADMIN_HOMEPAGE = "avoidRedirectAndGoStraightToWebAdminHomepage";
private String serverUrl;
private final ElementReference dataBrowserSearchField;
private final ElementReference dataBrowserItemSubtitle;
private final ElementReference dataBrowserSearchButton;
private final ElementReference dataBrowserTitle;
public WebadminWebdriverLibrary(WebDriverFacade wf, String serverUrl) throws InvocationTargetException, IllegalAccessException, InstantiationException {
super(wf);
setServerUrl( serverUrl );
dataBrowserTitle = new ElementReference(this, By.xpath( "//div[@id='data-area']//h3" ));
dataBrowserItemSubtitle = new ElementReference(this, By.xpath( "//div[@id='data-area']//div[@class='title']//p[@class='small']" ));
dataBrowserSearchField = new ElementReference(this, By.xpath( "//div[@id='data-console']//textarea" ));
dataBrowserSearchButton = new ElementReference(this, By.id( "data-execute-console" ));
}
public void setServerUrl(String url) {
serverUrl = url;
}
public void goToServerRoot() {
d.get( serverUrl );
}
public void goToWebadminStartPage() {
if(isUsingDevDotHTML()) {
d.get( serverUrl + "webadmin/dev.html" );
} else if(avoidRedirectAndGoStraightToWebAdminHomepage()) {
d.get( serverUrl + "webadmin/" );
} else {
goToServerRoot();
}
waitForTitleToBe( "Neo4j Monitoring and Management Tool" );
}
public void clickOnTab( String tabName )
{
ElementReference tab = getElement( By.xpath( "//*[@id='mainmenu']//a[contains(.,'" + tabName + "')]" ) );
new Condition<ElementReference>( new ElementClickable(), tab ).waitUntilFulfilled();
}
public void searchForInDataBrowser(String query) {
dataBrowserSearchField.waitUntilVisible();
executeScript("document.dataBrowserEditor.setValue(\""+query+"\")");
dataBrowserSearchButton.click();
}
public long createNodeInDataBrowser() {
goToWebadminStartPage();
clickOnTab( "Data browser" );
clickOnButton( "Node" );
return extractEntityIdFromLastSegmentOfUrl(getCurrentDatabrowserItemSubtitle());
}
public long createRelationshipInDataBrowser() {
createNodeInDataBrowser();
String prevItemHeadline = getCurrentDatabrowserItemSubtitle();
clickOnButton( "Relationship" );
getElement( By.id( "create-relationship-to" ) ).sendKeys( "0" );
clickOnButton( "Create" );
dataBrowserItemSubtitle.waitForTextToChangeFrom( prevItemHeadline );
return extractEntityIdFromLastSegmentOfUrl(getCurrentDatabrowserItemSubtitle());
}
public String getCurrentDatabrowserItemSubtitle() {
return getDataBrowserItemSubtitle().getText();
}
public ElementReference getDataBrowserItemSubtitle()
{
return dataBrowserItemSubtitle;
}
public ElementReference getDataBrowserItemTitle()
{
return dataBrowserTitle;
}
public void waitForSingleElementToAppear( By xpath )
{
waitForElementToAppear( xpath );
int numElems = d.findElements( xpath ).size();
if( numElems != 1) {
throw new ConditionFailedException("Expected single element, got " + numElems + " :(." , null);
}
}
private boolean isUsingDevDotHTML()
{
return System.getProperty( USE_DEV_HTML_FILE_KEY, "false" ).equals("true");
}
private boolean avoidRedirectAndGoStraightToWebAdminHomepage()
{
return System.getProperty( AVOID_REDIRECT_AND_GO_STRAIGHT_TO_WEB_ADMIN_HOMEPAGE, "false" ).equals("true");
}
public void confirmAll()
{
executeScript( "window.confirm=function(){return true;}", "" );
}
public Object executeScript(String script, Object ... args) {
if(d instanceof JavascriptExecutor ) {
JavascriptExecutor javascriptExecutor = (JavascriptExecutor) d;
return javascriptExecutor.executeScript( script, args);
} else {
throw new RuntimeException("Arbitrary script execution is only available for WebDrivers that implement " +
"the JavascriptExecutor interface.");
}
}
public void writeTo(By by, CharSequence ... toWrite) {
ElementReference el = getElement( by );
el.click();
el.clear();
el.sendKeys( toWrite );
}
private long extractEntityIdFromLastSegmentOfUrl(String url) {
return Long.valueOf(url.substring(url.lastIndexOf("/") + 1,url.length()));
}
}
| false
|
community_server_src_webtest_java_org_neo4j_server_webdriver_WebadminWebdriverLibrary.java
|
1,818
|
SauceLabsInternetExplorerWindows() {
public WebDriver createInstance() throws MalformedURLException
{
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability( "platform", Platform.VISTA );
capabilities.setCapability( "name", "Neo4j Web Testing" );
return WebdriverSauceLabsDriver.createDriver( capabilities );
}
};
| false
|
community_server_src_webtest_java_org_neo4j_server_webdriver_WebDriverFacade.java
|
1,819
|
SauceLabsChromeWindows() {
public WebDriver createInstance() throws MalformedURLException
{
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability( "platform", Platform.VISTA );
capabilities.setCapability( "name", "Neo4j Web Testing" );
return WebdriverSauceLabsDriver.createDriver( capabilities );
}
},
| false
|
community_server_src_webtest_java_org_neo4j_server_webdriver_WebDriverFacade.java
|
1,820
|
SauceLabsFirefoxWindows() {
public WebDriver createInstance() throws MalformedURLException
{
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability( "version", "5" );
capabilities.setCapability( "platform", Platform.VISTA );
capabilities.setCapability( "name", "Neo4j Web Testing" );
return WebdriverSauceLabsDriver.createDriver( capabilities );
}
},
| false
|
community_server_src_webtest_java_org_neo4j_server_webdriver_WebDriverFacade.java
|
1,821
|
Chrome() {
public WebDriver createInstance()
{
WebdriverChromeDriver.ensurePresent();
return new ChromeDriver();
}
},
| false
|
community_server_src_webtest_java_org_neo4j_server_webdriver_WebDriverFacade.java
|
1,822
|
public class JmxAttributeRepresentationDispatcher extends RepresentationDispatcher
{
@Override
protected Representation dispatchOtherProperty( Object property, String param )
{
if ( property instanceof CompositeData )
{
return dispatchCompositeData( (CompositeData) property );
}
else
{
return ValueRepresentation.string( property.toString() );
}
}
@Override
protected Representation dispatchOtherArray( Object[] property, String param )
{
if ( property instanceof CompositeData[] )
{
return dispatchCompositeDataArray( (CompositeData[]) property, param );
}
else
{
return super.dispatchOtherArray( property, param );
}
}
private JmxCompositeDataRepresentation dispatchCompositeData( CompositeData property )
{
return new JmxCompositeDataRepresentation( property );
}
private Representation dispatchCompositeDataArray( CompositeData[] property, String param )
{
ArrayList<Representation> values = new ArrayList<Representation>();
for ( CompositeData value : property )
{
values.add( new JmxCompositeDataRepresentation( value ) );
}
return new ListRepresentation( "", values );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_webadmin_rest_representations_JmxAttributeRepresentationDispatcher.java
|
1,823
|
public class ConsoleServiceRepresentation extends ServiceDefinitionRepresentation {
private Iterable<String> engines;
public ConsoleServiceRepresentation(String basePath, Iterable<String> engines)
{
super(basePath);
resourceUri( "exec", "" );
this.engines = engines;
}
@Override
public void serialize( MappingSerializer serializer )
{
super.serialize(serializer);
serializer.putList("engines", ListRepresentation.string(engines));
}
}
| false
|
community_server_src_main_java_org_neo4j_server_webadmin_rest_representations_ConsoleServiceRepresentation.java
|
1,824
|
public abstract class AbstractWebadminTest extends SharedServerTestBase {
public @Rule
TestData<JavaTestDocsGenerator> gen = TestData.producedThrough( JavaTestDocsGenerator.PRODUCER );
protected static WebadminWebdriverLibrary wl;
private static WebDriverFacade webdriverFacade;
@BeforeClass
public static void setup() throws Exception {
webdriverFacade = new WebDriverFacade();
wl = new WebadminWebdriverLibrary( webdriverFacade, deriveBaseUri() );
}
private static String deriveBaseUri()
{
// TODO: Deprecate "webdriver.override.neo-server.baseuri", SharedServerTestBase
// supports external servers now.
String overrideBaseUri = System.getProperty( "webdriver.override.neo-server.baseuri" );
if ( StringUtils.isNotEmpty( overrideBaseUri )) {
return overrideBaseUri;
}
return getServerURL();
}
@After
public void doc() {
gen.get().document("target/docs","webadmin");
}
protected void captureScreenshot( String string )
{
WebDriver webDriver = wl.getWebDriver();
if(webDriver instanceof TakesScreenshot)
{
try
{
File screenshotFile = ((TakesScreenshot)webDriver).getScreenshotAs(FILE);
File dir = new File("target/docs/webadmin/images");
dir.mkdirs();
String imageName = string+".png";
copyFile( screenshotFile, new File(dir, imageName) );
gen.get().addImageSnippet(string, imageName, gen.get().getTitle());
}
catch ( Exception e )
{
e.printStackTrace();
}
}
}
@Before
public void cleanTheDatabase() {
cleanDatabase();
}
@AfterClass
public static void tearDown() throws Exception {
webdriverFacade.quitBrowser();
}
private static void copyFile(File sourceFile, File destFile) throws IOException {
if(!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
destination.transferFrom(source, 0, source.size());
}
finally {
if(source != null) {
source.close();
}
if(destination != null) {
destination.close();
}
}
}
}
| false
|
community_server_src_webtest_java_org_neo4j_server_webadmin_AbstractWebadminTest.java
|
1,825
|
return new ArrayList<String>(){{
add("shell");
}};
| false
|
community_server_src_test_java_org_neo4j_server_webadmin_rest_ConsoleServiceDocTest.java
|
1,826
|
public class ConsoleServiceDocTest
{
private final URI uri = URI.create( "http://peteriscool.com:6666/" );
@Test
public void correctRepresentation() throws URISyntaxException, UnsupportedEncodingException
{
ConsoleService consoleService = new ConsoleService( new ShellOnlyConsoleSessionFactory(), databaseMock(),
DEV_NULL, new OutputFormat( new JsonFormat(), uri, null ) );
Response consoleResponse = consoleService.getServiceDefinition();
assertEquals( 200, consoleResponse.getStatus() );
String response = decode( consoleResponse );
assertThat( response, containsString( "resources" ) );
assertThat( response, containsString( uri.toString() ) );
}
@Test
public void advertisesAvailableConsoleEngines() throws URISyntaxException, UnsupportedEncodingException
{
ConsoleService consoleServiceWithJustShellEngine = new ConsoleService( new ShellOnlyConsoleSessionFactory(),
databaseMock(), DEV_NULL, new OutputFormat( new JsonFormat(), uri, null ) );
String response = decode( consoleServiceWithJustShellEngine.getServiceDefinition());
assertThat( response, containsString( "\"engines\" : [ \"shell\" ]" ) );
}
private Database databaseMock()
{
Database db = mock( Database.class );
when( db.getLogging() ).thenReturn( DEV_NULL );
return db;
}
private String decode( final Response response ) throws UnsupportedEncodingException
{
return new String( (byte[]) response.getEntity(), "UTF-8" );
}
private static class ShellOnlyConsoleSessionFactory implements ConsoleSessionFactory
{
@Override
public ScriptSession createSession(String engineName, Database database)
{
return null;
}
@Override
public Iterable<String> supportedEngines()
{
return new ArrayList<String>(){{
add("shell");
}};
}
}
}
| false
|
community_server_src_test_java_org_neo4j_server_webadmin_rest_ConsoleServiceDocTest.java
|
1,827
|
public class ConfigureEnabledManagementConsolesDocIT extends ExclusiveServerTestBase
{
private NeoServer server;
@After
public void stopTheServer()
{
server.stop();
}
@Test
public void shouldBeAbleToExplicitlySetConsolesToEnabled() throws Exception
{
server = server().withProperty( Configurator.MANAGEMENT_CONSOLE_ENGINES, "" )
.usingDatabaseDir( folder.getRoot().getAbsolutePath() )
.build();
server.start();
assertThat( exec( "ls", "shell" ).getStatus(), is( 400 ) );
}
@Test
public void shellConsoleShouldBeEnabledByDefault() throws Exception
{
server = server()
.usingDatabaseDir( folder.getRoot().getAbsolutePath() )
.build();
server.start();
assertThat( exec( "ls", "shell" ).getStatus(), is( 200 ) );
}
private JaxRsResponse exec( String command, String engine )
{
return RestRequest.req().post( server.baseUri() + "db/manage/server/console", "{" +
"\"engine\":\"" + engine + "\"," +
"\"command\":\"" + command + "\\n\"}" );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_webadmin_rest_ConfigureEnabledManagementConsolesDocIT.java
|
1,828
|
{
@Override
public Void call() throws Exception
{
server.stop();
return null;
}
} );
| false
|
community_server_src_test_java_org_neo4j_server_webadmin_rest_CommunityVersionAndEditionServiceDocIT.java
|
1,829
|
{
@Override
public Void call() throws Exception
{
server.start();
return null;
}
} );
| false
|
community_server_src_test_java_org_neo4j_server_webadmin_rest_CommunityVersionAndEditionServiceDocIT.java
|
1,830
|
public class CommunityVersionAndEditionServiceDocIT extends ExclusiveServerTestBase
{
private static NeoServer server;
private static FunctionalTestHelper functionalTestHelper;
@ClassRule
public static TemporaryFolder staticFolder = new TemporaryFolder();
public
@Rule
TestData<RESTDocsGenerator> gen = TestData.producedThrough( RESTDocsGenerator.PRODUCER );
private static FakeClock clock;
@Before
public void setUp()
{
gen.get().setSection( "dev/rest-api/database-version" );
}
@BeforeClass
public static void setupServer() throws Exception
{
clock = new FakeClock();
server = CommunityServerBuilder.server()
.usingDatabaseDir( staticFolder.getRoot().getAbsolutePath() )
.withClock( clock )
.build();
muteAll().call( new Callable<Void>()
{
@Override
public Void call() throws Exception
{
server.start();
return null;
}
} );
functionalTestHelper = new FunctionalTestHelper( server );
}
@Before
public void setupTheDatabase() throws Exception
{
// do nothing, we don't care about the database contents here
}
@AfterClass
public static void stopServer() throws Exception
{
muteAll().call( new Callable<Void>()
{
@Override
public Void call() throws Exception
{
server.stop();
return null;
}
} );
}
/**
* The Neo4j server hosts a resource that contains the edition (i.e. Community, Advanced or Enterprise) and
* version (e.g. 1.9.3 or 2.0.0) of the database. By accessing this resource via a HTTP GET, callers will know
* precisely which kind of database server is running.
*/
@Test
@Documented
@Title("Get the edition and version of the database")
public void shouldReportCommunityEdition() throws Exception
{
String releaseVersion = server.getDatabase().getGraph().getDependencyResolver().resolveDependency( KernelData
.class ).version().getReleaseVersion();
JaxRsResponse response = RestRequest.req().get( functionalTestHelper.managementUri() + "/" +
VersionAndEditionService.SERVER_PATH );
assertEquals( 200, response.getStatus() );
assertThat( response.getEntity(), containsString( "edition: \"community\"" ) );
assertThat( response.getEntity(), containsString( "version: \"" + releaseVersion + "\"" ) );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_webadmin_rest_CommunityVersionAndEditionServiceDocIT.java
|
1,831
|
{
@Override
public Void call() throws Exception
{
server.stop();
return null;
}
} );
| false
|
advanced_server-advanced_src_test_java_org_neo4j_server_webadmin_rest_AdvancedVersionAndEditionServiceIT.java
|
1,832
|
{
@Override
public Void call() throws Exception
{
AdvancedVersionAndEditionServiceIT.server.start();
return null;
}
} );
| false
|
advanced_server-advanced_src_test_java_org_neo4j_server_webadmin_rest_AdvancedVersionAndEditionServiceIT.java
|
1,833
|
public class AdvancedVersionAndEditionServiceIT extends ExclusiveServerTestBase
{
private static NeoServer server;
private static FunctionalTestHelper functionalTestHelper;
@ClassRule
public static TemporaryFolder staticFolder = new TemporaryFolder();
private static FakeClock clock;
@BeforeClass
public static void setupServer() throws Exception
{
clock = new FakeClock();
server = AdvancedServerBuilder.server()
.usingDatabaseDir( staticFolder.getRoot().getAbsolutePath() )
.withClock( clock )
.build();
muteAll().call( new Callable<Void>()
{
@Override
public Void call() throws Exception
{
AdvancedVersionAndEditionServiceIT.server.start();
return null;
}
} );
functionalTestHelper = new FunctionalTestHelper( AdvancedVersionAndEditionServiceIT.server );
}
@Before
public void setupTheDatabase() throws Exception
{
// do nothing, we don't care about the database contents here
}
@AfterClass
public static void stopServer() throws Exception
{
muteAll().call( new Callable<Void>()
{
@Override
public Void call() throws Exception
{
server.stop();
return null;
}
} );
}
@Test
public void shouldReportAdvancedEdition() throws Exception
{
String releaseVersion = server.getDatabase().getGraph().getDependencyResolver().resolveDependency( KernelData
.class ).version().getReleaseVersion();
JaxRsResponse response = RestRequest.req().get( functionalTestHelper.managementUri() + "/" +
VersionAndEditionService.SERVER_PATH );
assertEquals( 200, response.getStatus() );
assertThat( response.getEntity(), containsString( "edition: \"advanced\"" ) );
assertThat( response.getEntity(), containsString( "version: \"" + releaseVersion + "\"" ) );
}
}
| false
|
advanced_server-advanced_src_test_java_org_neo4j_server_webadmin_rest_AdvancedVersionAndEditionServiceIT.java
|
1,834
|
public class ShellSessionCreator implements ConsoleSessionCreator
{
@Override
public String name()
{
return "SHELL";
}
@Override
public ScriptSession newSession( Database database, CypherExecutor cypherExecutor )
{
return new ShellSession( database.getGraph() );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_webadmin_console_ShellSessionCreator.java
|
1,835
|
public class ShellSession implements ScriptSession
{
private static volatile ShellServer fallbackServer = null;
private final ShellClient client;
private final CollectingOutput output;
private final StringLogger log;
public ShellSession( GraphDatabaseAPI graph )
{
try
{
this.log = graph.getDependencyResolver().resolveDependency( Logging.class ).getMessagesLog( getClass() );
ShellServerKernelExtension extension = graph.getDependencyResolver().resolveDependency( KernelExtensions
.class ).resolveDependency( ShellServerKernelExtension.class );
ShellServer server = extension.getServer();
if ( server == null )
{
server = getFallbackServer( graph );
}
output = new CollectingOutput();
client = new SameJvmClient( new HashMap<String, Serializable>(), server, output );
output.asString();
}
catch ( RemoteException e )
{
throw new RuntimeException( "Unable to start shell client", e );
}
catch ( ShellException e )
{
throw new RuntimeException( "Unable to start shell client", e );
}
}
private ShellServer getFallbackServer( GraphDatabaseAPI graph )
{
if ( fallbackServer == null )
{
try
{
fallbackServer = new GraphDatabaseShellServer( graph, false );
}
catch ( RemoteException e )
{
throw new RuntimeException( "Unable to start the fallback shellserver", e );
}
}
return fallbackServer;
}
@Override
public Pair<String, String> evaluate( String script )
{
if ( script.equals( "init()" ) )
{
return Pair.of( "", client.getPrompt() );
}
if ( script.equals( "exit" ) || script.equals( "quit" ) )
{
return Pair.of( "Sorry, can't do that.", client.getPrompt() );
}
try
{
log.debug( script );
client.evaluate( removeInitialNewline( script ) );
return Pair.of( output.asString(), client.getPrompt() );
}
catch ( ShellException e )
{
String message = ((AbstractClient) client).shouldPrintStackTraces() ?
ShellException.stackTraceAsString( e ) : ShellException.getFirstMessage( e );
return Pair.of( message, client.getPrompt() );
}
}
private String removeInitialNewline( String script )
{
return script != null && script.startsWith( "\n" ) ? script.substring( 1 ) : script;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_webadmin_console_ShellSession.java
|
1,836
|
public class CypherSessionDocTest
{
@Test
public void shouldReturnASingleNode() throws Throwable
{
AbstractGraphDatabase graphdb = (AbstractGraphDatabase) new TestGraphDatabaseFactory().newImpermanentDatabase();
Database database = new WrappedDatabase( graphdb );
CypherExecutor executor = new CypherExecutor( database, StringLogger.DEV_NULL );
executor.start();
try
{
CypherSession session = new CypherSession( executor, DevNullLoggingService.DEV_NULL );
Pair<String, String> result = session.evaluate( "create (a) return a" );
assertThat( result.first(), containsString( "Node[0]" ) );
}
finally
{
graphdb.shutdown();
}
}
}
| false
|
community_server_src_test_java_org_neo4j_server_webadmin_console_CypherSessionDocTest.java
|
1,837
|
public class CypherSessionCreator implements ConsoleSessionCreator
{
@Override
public String name()
{
return "CYPHER";
}
@Override
public ScriptSession newSession( Database database, CypherExecutor cypherExecutor )
{
return new CypherSession( cypherExecutor, database.getLogging() );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_webadmin_console_CypherSessionCreator.java
|
1,838
|
public class CypherSession implements ScriptSession
{
private final CypherExecutor cypherExecutor;
private final ConsoleLogger log;
public CypherSession( CypherExecutor cypherExecutor, Logging logging )
{
this.cypherExecutor = cypherExecutor;
this.log = logging.getConsoleLog( getClass() );
}
@Override
public Pair<String, String> evaluate( String script )
{
if ( script.trim().equals( "" ) )
{
return Pair.of( "", null );
}
String resultString;
try
{
ExecutionResult result = cypherExecutor.getExecutionEngine().execute( script );
resultString = result.dumpToString();
}
catch ( SyntaxException error )
{
resultString = error.getMessage();
}
catch ( Exception exception )
{
log.error( "Unknown error executing cypher query", exception );
resultString = "Error: " + exception.getClass().getSimpleName() + " - " + exception.getMessage();
}
return Pair.of( resultString, null );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_webadmin_console_CypherSession.java
|
1,839
|
@Ignore("On avengers wall to be resolved")
public class ServerInfoWebIT extends AbstractWebadminTest {
@Test
public void canShowJMXValuesTest() {
wl.goToWebadminStartPage();
wl.clickOnTab("Server info");
wl.clickOnLink("Primitive count");
wl.waitForElementToAppear(By.xpath("//h2[contains(.,'Primitive count')]"));
}
}
| false
|
community_server_src_webtest_java_org_neo4j_server_webadmin_ServerInfoWebIT.java
|
1,840
|
@Ignore("On avengers wall to be resolved")
public class RedirectWebIT extends AbstractWebadminTest {
@Test
public void rootRedirectsToWebadminTest() {
wl.goToServerRoot();
wl.waitForUrlToBe(".+/webadmin/");
}
}
| false
|
community_server_src_webtest_java_org_neo4j_server_webadmin_RedirectWebIT.java
|
1,841
|
@Ignore("On avengers wall to be resolved")
public class IndexManagerWebIT extends AbstractWebadminTest {
@Test
public void createNodeIndexTest()
{
wl.goToWebadminStartPage();
wl.clickOnTab("Indexes");
wl.writeTo(By.id( "create-node-index-name" ), "mynodeindex");
wl.clickOn(By.xpath("//button[@class='create-node-index button']"));
wl.waitForSingleElementToAppear(By.xpath("//*[@id='node-indexes']//td[contains(.,'mynodeindex')]"));
}
@Test
public void createRelationshipIndexTest()
{
wl.goToWebadminStartPage();
wl.clickOnTab("Indexes");
wl.writeTo(By.id( "create-rel-index-name" ), "myrelindex");
wl.clickOn(By.xpath("//button[@class='create-rel-index button']"));
wl.waitForSingleElementToAppear(By.xpath("//*[@id='rel-indexes']//td[contains(.,'myrelindex')]"));
}
@Test
public void removeNodeIndexTest()
{
createNodeIndexTest();
wl.confirmAll();
wl.clickOn(By.xpath("//*[@id='node-indexes']//tr[contains(.,'mynodeindex')]//button[contains(.,'Delete')]"));
wl.waitForElementToDisappear(By.xpath("//*[@id='node-indexes']//td[contains(.,'mynodeindex')]"));
}
@Test
public void removeRelationshipIndexTest()
{
createRelationshipIndexTest();
wl.confirmAll();
wl.clickOn(By.xpath("//*[@id='rel-indexes']//tr[contains(.,'myrelindex')]//button[contains(.,'Delete')]"));
wl.waitForElementToDisappear(By.xpath("//*[@id='rel-indexes']//td[contains(.,'myrelindex')]"));
}
}
| false
|
community_server_src_webtest_java_org_neo4j_server_webadmin_IndexManagerWebIT.java
|
1,842
|
@Ignore("On avengers wall to be resolved")
public class DiscoverAvailableConsolesWebIT extends AbstractExclusiveServerWebadminTest
{
@Test
public void shouldShowOnlyShellIfAvailable() throws Exception
{
NeoServer server = server().build();
try
{
server.start();
setupWebdriver( server );
wl.goToWebadminStartPage();
wl.clickOnTab( "Console" );
wl.waitForElementToDisappear( By
.xpath( "//div[@id='console-tabs']//a[contains(.,'Gremlin')]" ) );
wl.waitForElementToAppear( By
.xpath( "//div[@id='console-tabs']//a[contains(.,'Neo4j Shell')]" ) );
}
finally
{
shutdownWebdriver();
server.stop();
}
}
@Test
public void shouldNotShowGremlinIfNotAvailable() throws Exception
{
NeoServer server = server().withProperty( Configurator.MANAGEMENT_CONSOLE_ENGINES, "shell" ).build();
try
{
server.start();
setupWebdriver( server );
wl.goToWebadminStartPage();
wl.clickOnTab( "Console" );
wl.waitForElementToDisappear( By
.xpath( "//div[@id='console-tabs']//a[contains(.,'Gremlin')]" ) );
wl.waitForElementToAppear( By
.xpath( "//div[@id='console-tabs']//a[contains(.,'Neo4j Shell')]" ) );
}
finally
{
shutdownWebdriver();
server.stop();
}
}
@Test
public void shouldNotShowEitherShellIfBothAreDisabled() throws Exception
{
NeoServer server = server().withProperty( Configurator.MANAGEMENT_CONSOLE_ENGINES, "" ).build();
try
{
server.start();
setupWebdriver( server );
wl.goToWebadminStartPage();
wl.clickOnTab( "Console" );
wl.waitForElementToDisappear( By
.xpath( "//div[@id='console-tabs']//a[contains(.,'Gremlin')]" ) );
wl.waitForElementToDisappear( By
.xpath( "//div[@id='console-tabs']//a[contains(.,'Neo4j Shell')]" ) );
}
finally
{
shutdownWebdriver();
server.stop();
}
}
}
| false
|
community_server_src_webtest_java_org_neo4j_server_webadmin_DiscoverAvailableConsolesWebIT.java
|
1,843
|
@Ignore("On avengers wall to be resolved")
public class DatabrowserWebIT extends AbstractWebadminTest {
//
// NODE MANAGEMENT
//
@Test
public void canFindNodeByNodePredicatedIdTest() {
long nodeId = wl.createNodeInDataBrowser();
wl.searchForInDataBrowser("node:" + nodeId);
wl.getDataBrowserItemSubtitle().waitForTextToChangeTo(".+/db/data/node/" + nodeId);
}
@Test
public void canFindNodeByIdTest() {
wl.createNodeInDataBrowser();
wl.searchForInDataBrowser("0");
wl.getDataBrowserItemSubtitle().waitForTextToChangeTo(".+/db/data/node/0");
}
@Test
public void canCreateNodeTest() {
wl.goToWebadminStartPage();
wl.clickOnTab("Data browser");
wl.clickOnButton("Node");
wl.getDataBrowserItemSubtitle().waitForTextToChangeFrom(".+/db/data/node/0");
wl.getDataBrowserItemSubtitle().waitForTextToChangeTo(".+/db/data/node/[0-9]+");
}
@Test
public void canSetNodePropertyTest() {
wl.goToWebadminStartPage();
wl.createNodeInDataBrowser();
wl.clickOnButton("Add property");
wl.waitForElementToAppear(By.xpath("//li[1]/ul/li//input[@class='property-key']"));
wl.writeTo(By.xpath("//li[1]/ul/li//input[@class='property-key']"), "mykey");
wl.writeTo(By.xpath("//li[1]/ul/li//input[@class='property-value']"), "12", Keys.RETURN);
wl.getElement(By.xpath("//div[@class='data-save-properties button']")).waitForTextToChangeTo("Saved");
wl.searchForInDataBrowser(wl.getCurrentDatabrowserItemSubtitle());
propertyShouldHaveValue("mykey","12");
}
//
// RELATIONSHIP MANAGEMENT
//
@Test
public void canCreateRelationshipTest() {
wl.createNodeInDataBrowser();
wl.clickOnButton("Relationship");
wl.writeTo(By.xpath("//input[@id='create-relationship-to']"), "0");
wl.clickOnButton("Create");
wl.getDataBrowserItemSubtitle().waitForTextToChangeTo(".+/db/data/relationship/[0-9]+");
}
@Test
public void canFindRelationshipByIdTest() {
long relId = wl.createRelationshipInDataBrowser();
wl.goToWebadminStartPage();
wl.clickOnTab("Data browser");
wl.searchForInDataBrowser("rel:" + relId);
wl.getDataBrowserItemSubtitle().waitForTextToChangeTo(".+/db/data/relationship/" + relId);
}
@Test
public void canSetRelationshipPropertiesTest() {
canCreateRelationshipTest();
wl.clickOnButton("Add property");
wl.waitForElementToAppear(By.xpath("//li[1]/ul/li//input[@class='property-key']"));
wl.writeTo(By.xpath("//li[1]/ul/li//input[@class='property-key']"), "mykey");
wl.writeTo(By.xpath("//li[1]/ul/li//input[@class='property-value']"), "12", Keys.RETURN);
wl.getElement(By.xpath("//div[@class='data-save-properties button']")).waitForTextToChangeTo("Saved");
wl.searchForInDataBrowser(wl.getCurrentDatabrowserItemSubtitle());
propertyShouldHaveValue("mykey","12");
}
//
// CYPHER
//
@Test
public void canExecuteCypherQueries() {
wl.searchForInDataBrowser("start n=node(0) return n,ID(n)");
wl.getElement(By.xpath("id('data-area')/div/div/table/tbody/tr[2]/td[2]")).waitForTextToChangeTo("0");
}
@Test
public void cypherResultHasClickableNodes() {
wl.searchForInDataBrowser("start n=node(0) return n,ID(n)");
wl.clickOn(By.xpath("id('data-area')/div/div/table/tbody/tr[2]/td[1]/a"));
wl.getDataBrowserItemSubtitle().waitForTextToChangeTo(".+/db/data/node/0");
}
private void propertyShouldHaveValue(String expectedKey, String expectedValue) {
ElementReference el = wl.getElement( By.xpath( "//input[@value='"+expectedKey+"']/../../..//input[@class='property-value']" ) );
assertThat(el.getValue(), is(expectedValue));
}
}
| false
|
community_server_src_webtest_java_org_neo4j_server_webadmin_DatabrowserWebIT.java
|
1,844
|
@Ignore("On avengers wall to be resolved")
public class ConsoleWebIT extends AbstractWebadminTest {
//
// SHELL
//
/**
* In order to access the Shell console,
* click on the "Console" tab in the webadmin
* and check the "Shell" link.
*
* @@screenshot_ShellConsole
*/
@Test
@Documented
public void accessing_the_Shell_console() {
wl.goToWebadminStartPage();
wl.clickOnTab("Console");
wl.clickOnLink("Neo4j Shell");
wl.waitForElementToAppear(By.xpath("//ul/li[contains(.,'neo4j-sh')]"));
captureScreenshot("screenshot_ShellConsole");
}
@Test
public void remembersShellStateWhenSwitchingTabsTest() {
wl.goToWebadminStartPage();
wl.clickOnTab("Console");
wl.clickOnLink("HTTP");
wl.clickOnTab("Data browser");
wl.clickOnTab("Console");
wl.waitForElementToAppear(By
.xpath("//li[contains(.,'200')]"));
}
@Test
@Ignore( "Broken due to http://code.google.com/p/selenium/issues/detail?id=1723" )
public void cypherHasMultilineInput()
{
accessing_the_Shell_console();
wl.writeTo(By.id("console-input"), "start a=node(1)", Keys.RETURN);
wl.writeTo(By.id("console-input"), "return a", Keys.RETURN);
wl.writeTo(By.id("console-input"), Keys.RETURN);
wl.waitForElementToAppear(By.xpath("//li[contains(.,'Node[0]')]"));
}
//
// HTTP CONSOLE
//
@Test
public void hasHttpConsoleTest() {
wl.goToWebadminStartPage();
wl.clickOnTab("Console");
wl.clickOnLink("HTTP");
wl.waitForElementToAppear(By.xpath("//p[contains(.,'HTTP Console')]"));
}
@Test
public void canAccessServerViaHttpConsoleTest() {
wl.goToWebadminStartPage();
wl.clickOnTab("Console");
wl.clickOnLink("HTTP");
wl.writeTo(By.id("console-input"), "GET /db/data/", Keys.RETURN);
wl.waitForElementToAppear(By.xpath("//li[contains(.,'200')]"));
}
@Test
public void httpConsoleShows404ProperlyTest() {
wl.goToWebadminStartPage();
wl.clickOnTab("Console");
wl.clickOnLink("HTTP");
wl.writeTo(By.id("console-input"), "GET /asd/ads/", Keys.RETURN);
wl.waitForElementToAppear(By.xpath("//li[contains(.,'404')]"));
}
@Test
public void httpConsoleShowsSyntaxErrorsTest() {
wl.goToWebadminStartPage();
wl.clickOnTab("Console");
wl.clickOnLink("HTTP");
wl.writeTo(By.id("console-input"), "blus 12 blah blah", Keys.RETURN);
wl.waitForElementToAppear(By.xpath("//li[contains(.,'Invalid')]"));
}
@Test
public void httpConsoleShowsJSONErrorsTest() {
wl.goToWebadminStartPage();
wl.clickOnTab("Console");
wl.clickOnLink("HTTP");
wl.writeTo(By.id("console-input"), "POST / {blah}", Keys.RETURN);
wl.waitForElementToAppear(By.xpath("//li[contains(.,'Invalid')]"));
}
}
| false
|
community_server_src_webtest_java_org_neo4j_server_webadmin_ConsoleWebIT.java
|
1,845
|
private static class ShellOnlyConsoleSessionFactory implements ConsoleSessionFactory
{
@Override
public ScriptSession createSession(String engineName, Database database)
{
return null;
}
@Override
public Iterable<String> supportedEngines()
{
return new ArrayList<String>(){{
add("shell");
}};
}
}
| false
|
community_server_src_test_java_org_neo4j_server_webadmin_rest_ConsoleServiceDocTest.java
|
1,846
|
public class EnterpriseVersionAndEditionServiceIT extends ExclusiveServerTestBase
{
private static NeoServer server;
private static FunctionalTestHelper functionalTestHelper;
@ClassRule
public static TemporaryFolder staticFolder = new TemporaryFolder();
private static FakeClock clock;
@BeforeClass
public static void setupServer() throws Exception
{
clock = new FakeClock();
server = EnterpriseServerBuilder.server()
.usingDatabaseDir( staticFolder.getRoot().getAbsolutePath() )
.withClock( clock )
.build();
muteAll().call( new Callable<Void>()
{
@Override
public Void call() throws Exception
{
server.start();
return null;
}
} );
functionalTestHelper = new FunctionalTestHelper( server );
}
@Before
public void setupTheDatabase() throws Exception
{
// do nothing, we don't care about the database contents here
}
@AfterClass
public static void stopServer() throws Exception
{
muteAll().call( new Callable<Void>()
{
@Override
public Void call() throws Exception
{
server.stop();
return null;
}
} );
}
@Test
public void shouldReportEnterpriseEdition() throws Exception
{
String releaseVersion = server.getDatabase().getGraph().getDependencyResolver().resolveDependency( KernelData
.class ).version().getReleaseVersion();
JaxRsResponse response = RestRequest.req().get( functionalTestHelper.managementUri() + "/" +
VersionAndEditionService.SERVER_PATH );
assertEquals( 200, response.getStatus() );
assertThat( response.getEntity(), containsString( "edition: \"enterprise\"" ) );
assertThat( response.getEntity(), containsString( "version: \"" + releaseVersion + "\"" ) );
}
}
| false
|
enterprise_server-enterprise_src_test_java_org_neo4j_server_webadmin_rest_EnterpriseVersionAndEditionServiceIT.java
|
1,847
|
public class SessionFactoryImpl implements ConsoleSessionFactory
{
private static final Collection<ConsoleSessionCreator> creators = IteratorUtil.asCollection( ServiceLoader.load( ConsoleSessionCreator.class ) );
private final HttpSession httpSession;
private final CypherExecutor cypherExecutor;
private final Map<String, ConsoleSessionCreator> engineCreators = new HashMap<String, ConsoleSessionCreator>();
public SessionFactoryImpl( HttpSession httpSession, List<String> supportedEngines, CypherExecutor cypherExecutor )
{
this.httpSession = httpSession;
this.cypherExecutor = cypherExecutor;
enableEngines( supportedEngines );
}
@Override
public ScriptSession createSession( String engineName, Database database )
{
engineName = engineName.toLowerCase();
if ( engineCreators.containsKey( engineName ) )
{
return getOrInstantiateSession( database, engineName + "-console-session", engineCreators.get( engineName ) );
}
throw new IllegalArgumentException( "Unknown console engine '" + engineName + "'." );
}
@Override
public Iterable<String> supportedEngines()
{
return engineCreators.keySet();
}
private ScriptSession getOrInstantiateSession( Database database, String key, ConsoleSessionCreator creator )
{
Object session = httpSession.getAttribute( key );
if ( session == null )
{
session = creator.newSession( database, cypherExecutor );
httpSession.setAttribute( key, session );
}
return (ScriptSession) session;
}
private void enableEngines( List<String> supportedEngines )
{
for ( ConsoleSessionCreator creator : creators )
{
for ( String engineName : supportedEngines )
{
if ( creator.name().equalsIgnoreCase( engineName ) )
{
engineCreators.put( engineName.toLowerCase(), creator );
}
}
}
}
}
| false
|
community_server_src_main_java_org_neo4j_server_webadmin_rest_console_SessionFactoryImpl.java
|
1,848
|
{
@Override
public Void call() throws Exception
{
server.start();
return null;
}
} );
| false
|
enterprise_server-enterprise_src_test_java_org_neo4j_server_webadmin_rest_EnterpriseVersionAndEditionServiceIT.java
|
1,849
|
@Path( ConsoleService.SERVICE_PATH )
public class ConsoleService implements AdvertisableService
{
public static final String SERVICE_PATH = "server/console";
private static final String SERVICE_NAME = "console";
private final ConsoleSessionFactory sessionFactory;
private final Database database;
private final OutputFormat output;
private final StringLogger log;
@SuppressWarnings("unchecked")
public ConsoleService( @Context Configuration config, @Context Database database, @Context HttpServletRequest req,
@Context OutputFormat output, @Context CypherExecutor cypherExecutor )
{
this( new SessionFactoryImpl(req.getSession(true ), config.getList(MANAGEMENT_CONSOLE_ENGINES, DEFAULT_MANAGEMENT_CONSOLE_ENGINES), cypherExecutor),
database, database.getLogging(), output );
}
public ConsoleService( ConsoleSessionFactory sessionFactory, Database database, Logging logging, OutputFormat output )
{
this.sessionFactory = sessionFactory;
this.database = database;
this.output = output;
this.log = logging.getMessagesLog( getClass() );
}
@Override
public String getName()
{
return SERVICE_NAME;
}
@Override
public String getServerPath()
{
return SERVICE_PATH;
}
@GET
public Response getServiceDefinition()
{
ConsoleServiceRepresentation result = new ConsoleServiceRepresentation( SERVICE_PATH, sessionFactory.supportedEngines() );
return output.ok( result );
}
@POST
public Response exec( @Context InputFormat input, String data )
{
Map<String, Object> args;
try
{
args = input.readMap( data );
}
catch ( BadInputException e )
{
return output.badRequest( e );
}
if ( !args.containsKey( "command" ) )
{
return Response.status( Status.BAD_REQUEST )
.entity( "Expected command argument not present." )
.build();
}
ScriptSession scriptSession;
try {
scriptSession = getSession( args );
} catch(IllegalArgumentException e) {
return output.badRequest(e);
}
log.debug( scriptSession.toString() );
try
{
Pair<String, String> result = scriptSession.evaluate( (String) args.get( "command" ) );
List<Representation> list = new ArrayList<Representation>(
asList( ValueRepresentation.string( result.first() ), ValueRepresentation.string( result.other() ) ) );
return output.ok( new ListRepresentation( RepresentationType.STRING, list ) );
} catch (Exception e)
{
List<Representation> list = new ArrayList<Representation>(
asList( ValueRepresentation.string( e.getClass() + " : " + e.getMessage() + "\n"), ValueRepresentation.string( null ) ));
return output.ok(new ListRepresentation( RepresentationType.STRING, list ));
}
}
private ScriptSession getSession( Map<String, Object> args )
{
return sessionFactory.createSession( (String) args.get( "engine" ), database );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_webadmin_rest_console_ConsoleService.java
|
1,850
|
private class FakeEnterpriseNeoServer extends FakeAdvancedNeoServer
{
}
| false
|
community_server_src_test_java_org_neo4j_server_webadmin_rest_VersionAndEditionServiceTest.java
|
1,851
|
private class FakeAdvancedNeoServer extends AbstractNeoServer
{
public FakeAdvancedNeoServer()
{
super( null );
}
@Override
protected PreFlightTasks createPreflightTasks()
{
throw new NotImplementedException();
}
@Override
protected Iterable<ServerModule> createServerModules()
{
throw new NotImplementedException();
}
@Override
protected Database createDatabase()
{
throw new NotImplementedException();
}
@Override
protected WebServer createWebServer()
{
throw new NotImplementedException();
}
@Override
public Iterable<AdvertisableService> getServices()
{
throw new NotImplementedException();
}
}
| false
|
community_server_src_test_java_org_neo4j_server_webadmin_rest_VersionAndEditionServiceTest.java
|
1,852
|
{
@Override
public Version version()
{
return version;
}
@Override
public GraphDatabaseAPI graphDatabase()
{
return graphDatabaseAPI;
}
};
| false
|
community_server_src_test_java_org_neo4j_server_webadmin_rest_VersionAndEditionServiceTest.java
|
1,853
|
public class VersionAndEditionServiceTest
{
@Test
public void shouldReturnReadableStringForServiceName() throws Exception
{
// given
VersionAndEditionService service = new VersionAndEditionService( mock( CommunityNeoServer.class ) );
// when
String serviceName = service.getName();
// then
assertEquals( "version", serviceName );
}
@Test
public void shouldReturnSensiblePathWhereServiceIsHosted() throws Exception
{
// given
VersionAndEditionService service = new VersionAndEditionService( mock( CommunityNeoServer.class ) );
// when
String serverPath = service.getServerPath();
// then
assertEquals( "server/version", serverPath );
}
@Test
public void shouldReturnDatabaseCommunityEditionAndVersion() throws Exception
{
// given
AbstractNeoServer neoServer = setUpMocksAndStub( CommunityNeoServer.class );
VersionAndEditionService service = new VersionAndEditionService( neoServer );
// when
Response response = service.getVersionAndEditionData();
// then
assertEquals( 200, response.getStatus() );
assertEquals( "{version: \"2.0.0\", edition: \"community\"}", response.getEntity().toString() );
}
@Test
public void shouldReturnDatabaseAdvancedEditionAndVersion() throws Exception
{
// given
AbstractNeoServer neoServer = setUpMocksAndStub( FakeAdvancedNeoServer.class );
VersionAndEditionService service = new VersionAndEditionService( neoServer );
// when
Response response = service.getVersionAndEditionData();
// then
assertEquals( 200, response.getStatus() );
assertEquals( "{version: \"2.0.0\", edition: \"advanced\"}", response.getEntity().toString() );
}
@Test
public void shouldReturnDatabaseEnterpriseEditionAndVersion() throws Exception
{
// given
AbstractNeoServer neoServer = setUpMocksAndStub( FakeEnterpriseNeoServer.class );
VersionAndEditionService service = new VersionAndEditionService( neoServer );
// when
Response response = service.getVersionAndEditionData();
// then
assertEquals( 200, response.getStatus() );
assertEquals( "{version: \"2.0.0\", edition: \"enterprise\"}", response.getEntity().toString() );
}
private AbstractNeoServer setUpMocksAndStub( Class<? extends AbstractNeoServer> serverClass )
{
AbstractNeoServer neoServer = mock( serverClass );
Database database = mock( Database.class );
final GraphDatabaseAPI graphDatabaseAPI = mock( GraphDatabaseAPI.class );
final Version version = mock( Version.class );
KernelData kernelData = stubKernelData( graphDatabaseAPI, version );
when( version.getReleaseVersion() ).thenReturn( "2.0.0" );
DependencyResolver dependencyResolver = mock( DependencyResolver.class );
when( graphDatabaseAPI.getDependencyResolver() ).thenReturn( dependencyResolver );
when( dependencyResolver.resolveDependency( KernelData.class ) ).thenReturn( kernelData );
when( database.getGraph() ).thenReturn( graphDatabaseAPI );
when( neoServer.getDatabase() ).thenReturn( database );
return neoServer;
}
private KernelData stubKernelData( final GraphDatabaseAPI graphDatabaseAPI, final Version version )
{
return new KernelData( new Config() )
{
@Override
public Version version()
{
return version;
}
@Override
public GraphDatabaseAPI graphDatabase()
{
return graphDatabaseAPI;
}
};
}
private class FakeAdvancedNeoServer extends AbstractNeoServer
{
public FakeAdvancedNeoServer()
{
super( null );
}
@Override
protected PreFlightTasks createPreflightTasks()
{
throw new NotImplementedException();
}
@Override
protected Iterable<ServerModule> createServerModules()
{
throw new NotImplementedException();
}
@Override
protected Database createDatabase()
{
throw new NotImplementedException();
}
@Override
protected WebServer createWebServer()
{
throw new NotImplementedException();
}
@Override
public Iterable<AdvertisableService> getServices()
{
throw new NotImplementedException();
}
}
private class FakeEnterpriseNeoServer extends FakeAdvancedNeoServer
{
}
}
| false
|
community_server_src_test_java_org_neo4j_server_webadmin_rest_VersionAndEditionServiceTest.java
|
1,854
|
@Path(VersionAndEditionService.SERVER_PATH)
public class VersionAndEditionService implements AdvertisableService
{
private NeoServer neoServer;
public static final String SERVER_PATH = "server/version";
public VersionAndEditionService( @Context NeoServer neoServer )
{
this.neoServer = neoServer;
}
@Override
public String getName()
{
return "version";
}
@Override
public String getServerPath()
{
return SERVER_PATH;
}
@GET
@Produces(APPLICATION_JSON)
public Response getVersionAndEditionData()
{
return Response.ok( "{version: \"" + neoDatabaseVersion( neoServer ) + "\", " +
"edition: \"" + neoServerEdition( neoServer ) + "\"}",
APPLICATION_JSON )
.build();
}
private String neoDatabaseVersion( NeoServer neoServer )
{
return neoServer.getDatabase().getGraph().getDependencyResolver().resolveDependency( KernelData.class )
.version().getReleaseVersion();
}
private String neoServerEdition( NeoServer neoServer )
{
String serverClassName = neoServer.getClass().getName().toLowerCase();
if ( serverClassName.contains( "enterpriseneoserver" ) )
{
return "enterprise";
}
else if ( serverClassName.contains( "advancedneoserver" ) )
{
return "advanced";
}
else if ( serverClassName.contains( "communityneoserver" ) )
{
return "community";
}
else
{
// return "unknown";
throw new IllegalStateException( "The Neo Server running is of unknown type. Valid types are Community, " +
"Advanced, and Enterprise." );
}
}
}
| false
|
community_server_src_main_java_org_neo4j_server_webadmin_rest_VersionAndEditionService.java
|
1,855
|
public class RootServiceDocTest
{
@Test
public void shouldAdvertiseServicesWhenAsked() throws Exception
{
UriInfo uriInfo = mock( UriInfo.class );
URI uri = new URI( "http://example.org:7474/" );
when( uriInfo.getBaseUri() ).thenReturn( uri );
RootService svc = new RootService( new CommunityNeoServer( DevNullLoggingService.DEV_NULL ) );
EntityOutputFormat output = new EntityOutputFormat( new JsonFormat(), null, null );
Response serviceDefinition = svc.getServiceDefinition( uriInfo, output );
assertEquals( 200, serviceDefinition.getStatus() );
Map<String, Object> result = (Map<String, Object>) output.getResultAsMap()
.get( "services" );
assertThat( result.get( "console" )
.toString(), containsString( String.format( "%sserver/console", uri.toString() ) ) );
assertThat( result.get( "jmx" )
.toString(), containsString( String.format( "%sserver/jmx", uri.toString() ) ) );
assertThat( result.get( "monitor" )
.toString(), containsString( String.format( "%sserver/monitor", uri.toString() ) ) );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_webadmin_rest_RootServiceDocTest.java
|
1,856
|
@Path("/")
public class RootService
{
private final NeoServer neoServer;
public RootService( @Context NeoServer neoServer )
{
this.neoServer = neoServer;
}
@GET
public Response getServiceDefinition( @Context UriInfo uriInfo, @Context OutputFormat output )
{
ServerRootRepresentation representation =
new ServerRootRepresentation( uriInfo.getBaseUri(), neoServer.getServices() );
return output.ok( representation );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_webadmin_rest_RootService.java
|
1,857
|
{{
add( "shell" );
}};
| false
|
community_server_src_test_java_org_neo4j_server_webadmin_rest_Neo4jShellConsoleSessionDocTest.java
|
1,858
|
public class Neo4jShellConsoleSessionDocTest implements ConsoleSessionFactory
{
private static final String LN = System.getProperty( "line.separator" );
private ConsoleService consoleService;
private Database database;
private final URI uri = URI.create( "http://peteriscool.com:6666/" );
@Before
public void setUp() throws Exception
{
this.database = new WrappedDatabase( (AbstractGraphDatabase) new TestGraphDatabaseFactory().
newImpermanentDatabaseBuilder().
setConfig( ShellSettings.remote_shell_enabled, Settings.TRUE ).
newGraphDatabase() );
this.consoleService = new ConsoleService(
this,
database,
DEV_NULL,
new OutputFormat( new JsonFormat(), uri, null ) );
}
@After
public void shutdownDatabase()
{
this.database.getGraph().shutdown();
}
@Override
public ScriptSession createSession( String engineName, Database database )
{
return new ShellSession( database.getGraph() );
}
@Test
public void doesntMangleNewlines() throws Exception
{
Response response = consoleService.exec( new JsonFormat(),
"{ \"command\" : \"create (n) return n;\", \"engine\":\"shell\" }" );
assertEquals( 200, response.getStatus() );
String result = decode( response ).get( 0 );
String expected = "+-----------+" + LN
+ "| n |" + LN
+ "+-----------+" + LN
+ "| Node[0]{} |" + LN
+ "+-----------+" + LN
+ "1 row";
assertThat( result, containsString( expected ) );
}
private List<String> decode( final Response response ) throws UnsupportedEncodingException, JsonParseException
{
return (List<String>) JsonHelper.readJson( new String( (byte[]) response.getEntity(), "UTF-8" ) );
}
@Override
public Iterable<String> supportedEngines()
{
return new ArrayList<String>()
{{
add( "shell" );
}};
}
}
| false
|
community_server_src_test_java_org_neo4j_server_webadmin_rest_Neo4jShellConsoleSessionDocTest.java
|
1,859
|
public class MonitorServiceDocTest implements JobScheduler
{
private RrdDbWrapper rrdDb;
private MonitorService monitorService;
private Database database;
private EntityOutputFormat output;
@Test
public void correctRepresentation() throws Exception
{
Response resp = monitorService.getServiceDefinition();
assertEquals( 200, resp.getStatus() );
Map<String, Object> resultAsMap = output.getResultAsMap();
@SuppressWarnings( "unchecked" ) Map<String, Object> resources = (Map<String, Object>) resultAsMap.get( "resources" );
assertThat( (String) resources.get( "data_from" ), containsString( "/fetch/{start}" ) );
assertThat( (String) resources.get( "data_period" ), containsString( "/fetch/{start}/{stop}" ) );
String latest_data = (String) resources.get( "latest_data" );
assertThat( latest_data, containsString( "/fetch" ) );
}
@Test
public void canFetchData() throws URISyntaxException, UnsupportedEncodingException
{
UriInfo mockUri = mock( UriInfo.class );
URI uri = new URI( "http://peteriscool.com:6666/" );
when( mockUri.getBaseUri() ).thenReturn( uri );
Response resp = monitorService.getData();
String entity = new String( (byte[]) resp.getEntity(), "UTF-8" );
assertEquals( entity, 200, resp.getStatus() );
assertThat( entity, containsString( "timestamps" ) );
assertThat( entity, containsString( "end_time" ) );
assertThat( entity, containsString( "property_count" ) );
}
@Before
public void setUp() throws Exception
{
database = new WrappedDatabase( (AbstractGraphDatabase) new TestGraphDatabaseFactory().newImpermanentDatabase() );
rrdDb = new RrdFactory( new SystemConfiguration(), DEV_NULL ).createRrdDbAndSampler( database, this );
output = new EntityOutputFormat( new JsonFormat(), URI.create( "http://peteriscool.com:6666/" ), null );
monitorService = new MonitorService( rrdDb.get(), output );
}
@After
public void shutdownDatabase() throws Throwable
{
try
{
rrdDb.close();
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
this.database.shutdown();
}
@Override
public void scheduleAtFixedRate( Runnable job, String jobName, long delay, long period )
{
}
}
| false
|
community_server_src_test_java_org_neo4j_server_webadmin_rest_MonitorServiceDocTest.java
|
1,860
|
@Path( MonitorService.ROOT_PATH )
public class MonitorService implements AdvertisableService
{
private final RrdDb rrdDb;
private final OutputFormat output;
public String getName()
{
return "monitor";
}
public String getServerPath()
{
return ROOT_PATH;
}
public MonitorService( @Context RrdDb rrdDb, @Context OutputFormat output )
{
this.rrdDb = rrdDb;
this.output = output;
}
public static final String ROOT_PATH = "server/monitor";
public static final String DATA_PATH = "/fetch";
public static final String DATA_FROM_PATH = DATA_PATH + "/{start}";
public static final String DATA_SPAN_PATH = DATA_PATH + "/{start}/{stop}";
public static final long MAX_TIMESPAN = DAYS.toSeconds( 365 * 5 );
public static final long DEFAULT_TIMESPAN = DAYS.toSeconds( 1 );
@GET
public Response getServiceDefinition()
{
ServiceDefinitionRepresentation sdr = new ServiceDefinitionRepresentation( ROOT_PATH );
sdr.resourceTemplate( "data_from", MonitorService.DATA_FROM_PATH );
sdr.resourceTemplate( "data_period", MonitorService.DATA_SPAN_PATH );
sdr.resourceUri( "latest_data", MonitorService.DATA_PATH );
return output.ok( sdr );
}
@GET
@Path( DATA_PATH )
public Response getData()
{
long time = Util.getTime();
return getData( time - DEFAULT_TIMESPAN, time );
}
@GET
@Path( DATA_FROM_PATH )
public Response getData( @PathParam( "start" ) long start )
{
return getData( start, Util.getTime() );
}
@GET
@Path( DATA_SPAN_PATH )
public Response getData( @PathParam( "start" ) long start, @PathParam( "stop" ) long stop )
{
if ( start >= stop || ( stop - start ) > MAX_TIMESPAN )
{
return output.badRequest(
new IllegalArgumentException( format(
"Start time must be before stop time, and the " +
"total time span can be no bigger than " +
"%dms. Time span was %dms.",
MAX_TIMESPAN, ( stop - start ) ) ) );
}
try
{
FetchRequest request = rrdDb.createFetchRequest( AVERAGE, start, stop );
return output.ok( new RrdDataRepresentation( request.fetchData() ) );
}
catch ( Exception e )
{
return output.serverError( e );
}
}
}
| false
|
community_server_src_main_java_org_neo4j_server_webadmin_rest_MonitorService.java
|
1,861
|
public class MasterInfoServiceTest
{
@Test
public void masterShouldRespond200AndTrueWhenMaster() throws Exception
{
// given
HighlyAvailableGraphDatabase database = mock( HighlyAvailableGraphDatabase.class );
when( database.role() ).thenReturn( "master" );
MasterInfoService service = new MasterInfoService( null, database );
// when
Response response = service.isMaster();
// then
assertEquals( 200, response.getStatus() );
assertEquals( "true", String.valueOf( response.getEntity() ) );
}
@Test
public void masterShouldRespond404AndFalseWhenSlave() throws Exception
{
// given
HighlyAvailableGraphDatabase database = mock( HighlyAvailableGraphDatabase.class );
when( database.role() ).thenReturn( "slave" );
MasterInfoService service = new MasterInfoService( null, database );
// when
Response response = service.isMaster();
// then
assertEquals( 404, response.getStatus() );
assertEquals( "false", String.valueOf( response.getEntity() ) );
}
@Test
public void masterShouldRespond404AndUNKNOWNWhenUnknown() throws Exception
{
// given
HighlyAvailableGraphDatabase database = mock( HighlyAvailableGraphDatabase.class );
when( database.role() ).thenReturn( "unknown" );
MasterInfoService service = new MasterInfoService( null, database );
// when
Response response = service.isMaster();
// then
assertEquals( 404, response.getStatus() );
assertEquals( "UNKNOWN", String.valueOf( response.getEntity() ) );
}
@Test
public void slaveShouldRespond200AndTrueWhenSlave() throws Exception
{
// given
HighlyAvailableGraphDatabase database = mock( HighlyAvailableGraphDatabase.class );
when( database.role() ).thenReturn( "slave" );
MasterInfoService service = new MasterInfoService( null, database );
// when
Response response = service.isSlave();
// then
assertEquals( 200, response.getStatus() );
assertEquals( "true", String.valueOf( response.getEntity() ) );
}
@Test
public void slaveShouldRespond404AndFalseWhenMaster() throws Exception
{
// given
HighlyAvailableGraphDatabase database = mock( HighlyAvailableGraphDatabase.class );
when( database.role() ).thenReturn( "master" );
MasterInfoService service = new MasterInfoService( null, database );
// when
Response response = service.isSlave();
// then
assertEquals( 404, response.getStatus() );
assertEquals( "false", String.valueOf( response.getEntity() ) );
}
@Test
public void slaveShouldRespond404AndUNKNOWNWhenUnknown() throws Exception
{
// given
HighlyAvailableGraphDatabase database = mock( HighlyAvailableGraphDatabase.class );
when( database.role() ).thenReturn( "unknown" );
MasterInfoService service = new MasterInfoService( null, database );
// when
Response response = service.isSlave();
// then
assertEquals( 404, response.getStatus() );
assertEquals( "UNKNOWN", String.valueOf( response.getEntity() ) );
}
@Test
public void shouldReportMasterAsGenerallyAvailableForTransactionProcessing() throws Exception
{
// given
HighlyAvailableGraphDatabase database = mock( HighlyAvailableGraphDatabase.class );
when( database.role() ).thenReturn( "master" );
MasterInfoService service = new MasterInfoService( null, database );
// when
Response response = service.isAvailable();
// then
assertEquals( 200, response.getStatus() );
assertEquals( "master", String.valueOf( response.getEntity() ) );
}
@Test
public void shouldReportSlaveAsGenerallyAvailableForTransactionProcessing() throws Exception
{
// given
HighlyAvailableGraphDatabase database = mock( HighlyAvailableGraphDatabase.class );
when( database.role() ).thenReturn( "slave" );
MasterInfoService service = new MasterInfoService( null, database );
// when
Response response = service.isAvailable();
// then
assertEquals( 200, response.getStatus() );
assertEquals( "slave", String.valueOf( response.getEntity() ) );
}
@Test
public void shouldReportNonMasterOrSlaveAsUnavailableForTransactionProcessing() throws Exception
{
// given
HighlyAvailableGraphDatabase database = mock( HighlyAvailableGraphDatabase.class );
when( database.role() ).thenReturn( "unknown" );
MasterInfoService service = new MasterInfoService( null, database );
// when
Response response = service.isAvailable();
// then
assertEquals( 404, response.getStatus() );
assertEquals( "UNKNOWN", String.valueOf( response.getEntity() ) );
}
}
| false
|
enterprise_server-enterprise_src_test_java_org_neo4j_server_webadmin_rest_MasterInfoServiceTest.java
|
1,862
|
@Path(MasterInfoService.BASE_PATH)
public class MasterInfoService implements AdvertisableService
{
public static final String BASE_PATH = "server/ha";
public static final String IS_MASTER_PATH = "/master";
public static final String IS_SLAVE_PATH = "/slave";
public static final String IS_AVAILABLE_PATH = "/available";
private final OutputFormat output;
private final HighlyAvailableGraphDatabase haDb;
public MasterInfoService( @Context OutputFormat output, @Context GraphDatabaseService db )
{
this.output = output;
if ( db instanceof HighlyAvailableGraphDatabase )
{
this.haDb = (HighlyAvailableGraphDatabase) db;
}
else
{
this.haDb = null;
}
}
@GET
public Response discover() throws BadInputException
{
if ( haDb == null )
{
return status( FORBIDDEN ).build();
}
String isMasterUri = IS_MASTER_PATH;
String isSlaveUri = IS_SLAVE_PATH;
HaDiscoveryRepresentation dr = new HaDiscoveryRepresentation( BASE_PATH, isMasterUri, isSlaveUri );
return output.ok( dr );
}
@GET
@Path(IS_MASTER_PATH)
public Response isMaster() throws BadInputException
{
if ( haDb == null )
{
return status( FORBIDDEN ).build();
}
String role = haDb.role().toLowerCase();
if ( role.equals( "master" ))
{
return positiveResponse();
}
if ( role.equals( "slave" ))
{
return negativeResponse();
}
return unknownResponse();
}
@GET
@Path(IS_SLAVE_PATH)
public Response isSlave() throws BadInputException
{
if ( haDb == null )
{
return status( FORBIDDEN ).build();
}
String role = haDb.role().toLowerCase();
if ( role.equals( "slave" ))
{
return positiveResponse();
}
if ( role.equals( "master" ))
{
return negativeResponse();
}
return unknownResponse();
}
@GET
@Path( IS_AVAILABLE_PATH )
public Response isAvailable()
{
if ( haDb == null )
{
return status( FORBIDDEN ).build();
}
String role = haDb.role().toLowerCase();
if ( "slave".equals( role ) || "master".equals( role ))
{
return plainTextResponse( OK, role );
}
return unknownResponse();
}
private Response negativeResponse()
{
return plainTextResponse( NOT_FOUND, "false" );
}
private Response positiveResponse()
{
return plainTextResponse( OK, "true" );
}
private Response unknownResponse()
{
return plainTextResponse( NOT_FOUND, "UNKNOWN" );
}
private Response plainTextResponse( Response.Status status, String entityBody )
{
return status( status ).type( TEXT_PLAIN_TYPE ).entity( entityBody ).build();
}
@Override
public String getName()
{
return "ha";
}
@Override
public String getServerPath()
{
return BASE_PATH;
}
}
| false
|
enterprise_server-enterprise_src_main_java_org_neo4j_server_webadmin_rest_MasterInfoService.java
|
1,863
|
public class MasterInfoServerModule implements ServerModule
{
private final WebServer server;
private final Configuration config;
private final ConsoleLogger log;
public MasterInfoServerModule( WebServer server, Configuration config, Logging logging )
{
this.server = server;
this.config = config;
this.log = logging.getConsoleLog( getClass() );
}
@Override
public void start()
{
URI baseUri = managementApiUri();
server.addJAXRSClasses( getClassNames(), baseUri.toString(), null );
log.log( "Mounted REST API at: " + baseUri.toString() );
}
@Override
public void stop()
{
URI baseUri = managementApiUri();
server.removeJAXRSClasses( getClassNames(), baseUri.toString() );
}
private List<String> getClassNames()
{
return listFrom( MasterInfoService.class.getName() );
}
private URI managementApiUri()
{
return URI.create( config.getString( Configurator.MANAGEMENT_PATH_PROPERTY_KEY,
Configurator.DEFAULT_MANAGEMENT_API_PATH ) );
}
}
| false
|
enterprise_server-enterprise_src_main_java_org_neo4j_server_webadmin_rest_MasterInfoServerModule.java
|
1,864
|
public class JmxServiceDocTest
{
public JmxService jmxService;
private final URI uri = URI.create( "http://peteriscool.com:6666/" );
@Test
public void correctRepresentation() throws URISyntaxException, UnsupportedEncodingException
{
Response resp = jmxService.getServiceDefinition();
assertEquals( 200, resp.getStatus() );
String json = new String( (byte[]) resp.getEntity(), "UTF-8" );
assertThat( json, containsString( "resources" ) );
assertThat( json, containsString( uri.toString() ) );
assertThat( json, containsString( "jmx/domain/{domain}/{objectName}" ) );
}
@Test
public void shouldListDomainsCorrectly() throws Exception
{
Response resp = jmxService.listDomains();
assertEquals( 200, resp.getStatus() );
}
@Test
public void testwork() throws Exception
{
jmxService.queryBeans( "[\"*:*\"]" );
}
@Before
public void setUp() throws Exception
{
this.jmxService = new JmxService( new OutputFormat( new JsonFormat(), uri, null ), null );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_webadmin_rest_JmxServiceDocTest.java
|
1,865
|
@Path(JmxService.ROOT_PATH)
public class JmxService implements AdvertisableService
{
public static final String ROOT_PATH = "server/jmx";
public static final String DOMAINS_PATH = "/domain";
public static final String DOMAIN_TEMPLATE = DOMAINS_PATH + "/{domain}";
public static final String BEAN_TEMPLATE = DOMAIN_TEMPLATE + "/{objectName}";
public static final String QUERY_PATH = "/query";
public static final String KERNEL_NAME_PATH = "/kernelquery";
private final OutputFormat output;
public JmxService( @Context OutputFormat output, @Context InputFormat input )
{
this.output = output;
}
@GET
public Response getServiceDefinition()
{
ServiceDefinitionRepresentation serviceDef = new ServiceDefinitionRepresentation( ROOT_PATH );
serviceDef.resourceUri( "domains", JmxService.DOMAINS_PATH );
serviceDef.resourceTemplate( "domain", JmxService.DOMAIN_TEMPLATE );
serviceDef.resourceTemplate( "bean", JmxService.BEAN_TEMPLATE );
serviceDef.resourceUri( "query", JmxService.QUERY_PATH );
serviceDef.resourceUri( "kernelquery", JmxService.KERNEL_NAME_PATH );
return output.ok( serviceDef );
}
@GET
@Path(DOMAINS_PATH)
public Response listDomains() throws NullPointerException
{
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
ListRepresentation domains = ListRepresentation.strings( server.getDomains() );
return output.ok( domains );
}
@GET
@Path(DOMAIN_TEMPLATE)
public Response getDomain( @PathParam("domain") String domainName )
{
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
JmxDomainRepresentation domain = new JmxDomainRepresentation( domainName );
for ( Object objName : server.queryNames( null, null ) )
{
if ( objName.toString()
.startsWith( domainName ) )
{
domain.addBean( (ObjectName) objName );
}
}
return output.ok( domain );
}
@GET
@Path(BEAN_TEMPLATE)
public Response getBean( @PathParam("domain") String domainName, @PathParam("objectName") String objectName )
{
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
ArrayList<JmxMBeanRepresentation> beans = new ArrayList<JmxMBeanRepresentation>();
for ( Object objName : server.queryNames( createObjectName( domainName, objectName ), null ) )
{
beans.add( new JmxMBeanRepresentation( (ObjectName) objName ) );
}
return output.ok( new ListRepresentation( "bean", beans ) );
}
private ObjectName createObjectName( final String domainName, final String objectName )
{
try
{
return new ObjectName( domainName + ":" + URLDecoder.decode( objectName, "UTF-8" ) );
}
catch ( MalformedObjectNameException e )
{
throw new WebApplicationException( e, 400 );
}
catch ( UnsupportedEncodingException e )
{
throw new WebApplicationException( e, 400 );
}
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path(QUERY_PATH)
@SuppressWarnings("unchecked")
public Response queryBeans( String query )
{
try
{
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
String json = dodgeStartingUnicodeMarker( query );
Collection<Object> queries = (Collection<Object>) JsonHelper.jsonToSingleValue( json );
ArrayList<JmxMBeanRepresentation> beans = new ArrayList<JmxMBeanRepresentation>();
for ( Object queryObj : queries )
{
assert queryObj instanceof String;
for ( Object objName : server.queryNames( new ObjectName( (String) queryObj ), null ) )
{
beans.add( new JmxMBeanRepresentation( (ObjectName) objName ) );
}
}
return output.ok( new ListRepresentation( "jmxBean", beans ) );
}
catch ( MalformedObjectNameException e )
{
return output.badRequest( e );
}
catch ( BadInputException e )
{
return output.badRequest( e );
}
}
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Path(QUERY_PATH)
public Response formQueryBeans( @FormParam("value") String data )
{
return queryBeans( data );
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path(KERNEL_NAME_PATH)
public Response currentKernelInstance( @Context Database database )
{
Kernel kernelBean = database.getGraph().getDependencyResolver().resolveDependency( JmxKernelExtension.class )
.getSingleManagementBean( Kernel.class );
return Response.ok( "\"" + kernelBean.getMBeanQuery()
.toString() + "\"" )
.type( MediaType.APPLICATION_JSON )
.build();
}
public String getName()
{
return "jmx";
}
public String getServerPath()
{
return ROOT_PATH;
}
private static String dodgeStartingUnicodeMarker( String string )
{
if ( string != null && string.length() > 0 )
{
if ( string.charAt( 0 ) == 0xfeff )
{
return string.substring( 1 );
}
}
return string;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_webadmin_rest_JmxService.java
|
1,866
|
public class HaDiscoveryRepresentation extends MappingRepresentation
{
private static final String MASTER_KEY = "master";
private static final String SLAVE_KEY = "slave";
private static final String DISCOVERY_REPRESENTATION_TYPE = "discovery";
private final String basePath;
private final String isMasterUri;
private final String isSlaveUri;
public HaDiscoveryRepresentation( String basePath, String isMasterUri, String isSlaveUri )
{
super( DISCOVERY_REPRESENTATION_TYPE );
this.basePath = basePath;
this.isMasterUri = isMasterUri;
this.isSlaveUri = isSlaveUri;
}
@Override
protected void serialize( MappingSerializer serializer )
{
serializer.putUri( MASTER_KEY, basePath + isMasterUri );
serializer.putUri( SLAVE_KEY, basePath + isSlaveUri );
}
}
| false
|
enterprise_server-enterprise_src_main_java_org_neo4j_server_webadmin_rest_HaDiscoveryRepresentation.java
|
1,867
|
{
@Override
public Void call() throws Exception
{
server.stop();
return null;
}
} );
| false
|
enterprise_server-enterprise_src_test_java_org_neo4j_server_webadmin_rest_EnterpriseVersionAndEditionServiceIT.java
|
1,868
|
{
private final TemporaryFolder folder = new TemporaryFolder();
@Override
public File root()
{
return folder.getRoot();
}
@Override
public void delete()
{
folder.delete();
}
@Override
public void create() throws IOException
{
folder.create();
}
};
| false
|
community_kernel_src_test_java_org_neo4j_test_EmbeddedDatabaseRule.java
|
1,869
|
{
private final TargetDirectory targetDirectory = TargetDirectory.forTest( testClass );
private File dbDir;
@Override
public File root()
{
return dbDir;
}
@Override
public void delete() throws IOException
{
targetDirectory.cleanup();
}
@Override
public void create()
{
dbDir = targetDirectory.makeGraphDbDir();
}
};
| false
|
community_kernel_src_test_java_org_neo4j_test_EmbeddedDatabaseRule.java
|
1,870
|
public class EphemeralFileSystemRule extends ExternalResource
{
private EphemeralFileSystemAbstraction fs = new EphemeralFileSystemAbstraction();
@Override
protected void after()
{
fs.shutdown();
}
public EphemeralFileSystemAbstraction get()
{
return fs;
}
public EphemeralFileSystemAbstraction snapshot( Runnable action )
{
EphemeralFileSystemAbstraction snapshot = fs.snapshot();
try
{
action.run();
}
finally
{
fs.shutdown();
fs = snapshot;
}
return fs;
}
public static Runnable shutdownDb( final GraphDatabaseService db )
{
return new Runnable()
{
@Override
public void run()
{
db.shutdown();
}
};
}
}
| false
|
community_kernel_src_test_java_org_neo4j_test_EphemeralFileSystemRule.java
|
1,871
|
public class Script extends ConfigurationParser
{
public Script( File config, String... format )
{
super( config, format );
}
public Script( String... format )
{
super( format );
}
protected String storeDir;
public static <S extends Script> S initialize( Class<S> scriptClass, String... args )
{
if ( args.length < 1 )
{
throw new IllegalArgumentException(
"GraphvizWriter expects at least one argument, the path "
+ "to the Neo4j storage dir." );
}
String[] format = new String[args.length - 1];
System.arraycopy( args, 1, format, 0, format.length );
String configFile = System.getProperty( "org.neo4j.visualization.ConfigFile", null );
S script = null;
try
{
Constructor<S> ctor;
if ( configFile != null ) // Try invoking with configuration file
{
try
{
ctor = scriptClass.getConstructor( File.class, String[].class );
script = ctor.newInstance( new File( configFile ), format );
}
catch ( NoSuchMethodException handled )
{
if ( format == null || format.length == 0 )
{
try
{
ctor = scriptClass.getConstructor( File.class );
script = ctor.newInstance( new File( configFile ) );
}
catch ( NoSuchMethodException fallthrough )
{
// Ignore
}
}
}
}
if ( script == null ) // Not created with configuration file
{
try
{
ctor = scriptClass.getConstructor( String[].class );
script = ctor.newInstance( (Object) format );
}
catch ( NoSuchMethodException exception )
{
if ( format == null || format.length == 0 )
{
script = scriptClass.newInstance();
}
else
{
throw exception;
}
}
}
}
catch ( NoSuchMethodException e )
{
throw new UnsupportedOperationException( scriptClass.getName()
+ " does not have a suitable constructor", e );
}
catch ( InvocationTargetException e )
{
throw new UnsupportedOperationException( "Could not initialize script",
e.getTargetException() );
}
catch ( Exception e )
{
throw new UnsupportedOperationException( "Could not initialize script", e );
}
script.storeDir = args[0];
return script;
}
public static void main( Class<? extends Script> scriptClass, String... args )
{
initialize( scriptClass, args ).emit(
new File( System.getProperty( "graphviz.out", "graph.dot" ) ) );
}
/**
* @param args The command line arguments.
*/
public static void main( String... args )
{
main( Script.class, args );
}
public final void emit( File outfile )
{
GraphDatabaseService graphdb = createGraphDb();
GraphvizWriter writer = new GraphvizWriter( styles() );
try
{
try ( Transaction tx = graphdb.beginTx() )
{
writer.emit( outfile, createGraphWalker( graphdb ) );
}
}
catch ( IOException e )
{
e.printStackTrace();
}
finally
{
graphdb.shutdown();
}
}
protected String storeDir()
{
return storeDir;
}
protected GraphDatabaseService createGraphDb()
{
return new GraphDatabaseFactory().newEmbeddedDatabase( storeDir() );
}
protected Walker createGraphWalker( GraphDatabaseService graphdb )
{
return Walker.fullGraph( graphdb );
}
}
| false
|
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_Script.java
|
1,872
|
private class PropertyAdapter implements PropertyRenderer<IOException>
{
private final PropertyContainerStyle style;
PropertyAdapter( Node node ) throws IOException
{
nodeStyle.emitNodeStart( stream, node );
this.style = nodeStyle;
}
PropertyAdapter( Relationship relationship ) throws IOException
{
edgeStyle.emitRelationshipStart( stream, relationship );
this.style = edgeStyle;
}
public void done() throws IOException
{
style.emitEnd( stream );
}
public void renderProperty( String propertyKey, Object propertyValue )
throws IOException
{
style.emitProperty( stream, propertyKey, propertyValue );
}
}
| false
|
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_GraphvizRenderer.java
|
1,873
|
class GraphvizRenderer implements GraphRenderer<IOException>
{
private final PrintStream stream;
private final GraphStyle graphStyle;
private final NodeStyle nodeStyle;
private final RelationshipStyle edgeStyle;
GraphvizRenderer( GraphStyle style, PrintStream stream ) throws IOException
{
this.stream = stream;
nodeStyle = style.nodeStyle;
edgeStyle = style.edgeStyle;
graphStyle = style;
graphStyle.emitGraphStart( stream );
}
public void done() throws IOException
{
graphStyle.emitGraphEnd( stream );
}
public PropertyRenderer<IOException> renderNode( Node node )
throws IOException
{
return new PropertyAdapter( node );
}
public PropertyRenderer<IOException> renderRelationship(
Relationship relationship ) throws IOException
{
return new PropertyAdapter( relationship );
}
public GraphvizRenderer renderSubgraph( String name ) throws IOException
{
return new GraphvizRenderer( graphStyle.getSubgraphStyle( name ), stream );
}
private class PropertyAdapter implements PropertyRenderer<IOException>
{
private final PropertyContainerStyle style;
PropertyAdapter( Node node ) throws IOException
{
nodeStyle.emitNodeStart( stream, node );
this.style = nodeStyle;
}
PropertyAdapter( Relationship relationship ) throws IOException
{
edgeStyle.emitRelationshipStart( stream, relationship );
this.style = edgeStyle;
}
public void done() throws IOException
{
style.emitEnd( stream );
}
public void renderProperty( String propertyKey, Object propertyValue )
throws IOException
{
style.emitProperty( stream, propertyKey, propertyValue );
}
}
}
| false
|
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_GraphvizRenderer.java
|
1,874
|
static final class Header
{
private Header()
{
String prefix = getClass().getPackage().getName() + ".";
String nodePrefix = prefix + "node.";
String relPrefix = prefix + "relationship.";
Properties properties = System.getProperties();
for ( Object obj : properties.keySet() )
{
try
{
String property = ( String ) obj;
if ( property.startsWith( nodePrefix ) )
{
nodeHeader.put( property
.substring( nodePrefix.length() ),
( String ) properties.get( property ) );
}
else if ( property.startsWith( relPrefix ) )
{
edgeHeader.put(
property.substring( relPrefix.length() ),
( String ) properties.get( property ) );
}
}
catch ( ClassCastException cce )
{
continue;
}
}
assertMember( nodeHeader, properties, prefix, "fontname",
"Bitstream Vera Sans" );
assertMember( nodeHeader, properties, prefix, "fontsize", "8" );
assertMember( edgeHeader, properties, prefix, "fontname",
"Bitstream Vera Sans" );
assertMember( edgeHeader, properties, prefix, "fontsize", "8" );
nodeHeader.put( "shape", "Mrecord" );
}
final Map<String, String> nodeHeader = new HashMap<String, String>();
final Map<String, String> edgeHeader = new HashMap<String, String>();
final Map<String, String> graphHeader = new HashMap<String, String>();
private void assertMember( Map<String, String> header,
Properties properties, String prefix, String key, String def )
{
if ( !header.containsKey( key ) )
{
header.put( key, properties.getProperty( prefix + key, def ) );
}
}
private void emitNode( Appendable stream ) throws IOException
{
emitHeader( stream, nodeHeader );
}
private void emitEdge( Appendable stream ) throws IOException
{
emitHeader( stream, edgeHeader );
}
}
| false
|
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_GraphStyle.java
|
1,875
|
{
@Override
protected void emitGraphStart( Appendable stream ) throws IOException
{
stream.append( String.format( " subgraph cluster_%s {", subgraphName ) );
}
@Override
protected void emitGraphEnd( Appendable stream ) throws IOException
{
stream.append( String.format( " label = \"%s\"\n }\n", subgraphName ) );
}
};
| false
|
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_GraphStyle.java
|
1,876
|
public class GraphStyle
{
GraphStyle( StyleParameter... parameters )
{
this.configuration = new DefaultStyleConfiguration( parameters );
this.nodeStyle = new DefaultNodeStyle( configuration );
this.edgeStyle = new DefaultRelationshipStyle( configuration );
}
/**
* Constructor for subclasses. Used to provide graph styles with more
* elaborate configuration than the default configuration parameters can
* provide.
* @param nodeStyle
* the node style to use.
* @param edgeStyle
* the relationship style to use.
*/
public GraphStyle( NodeStyle nodeStyle, RelationshipStyle edgeStyle )
{
this.configuration = null;
this.nodeStyle = nodeStyle;
this.edgeStyle = edgeStyle;
}
/**
* Emit the end of a graph. Override this method to change the format of the
* end of a graph.
* @param stream
* the stream to emit the graph ending to.
* @throws IOException
* if there is an error in emitting the graph ending.
*/
protected void emitGraphEnd( Appendable stream ) throws IOException
{
stream.append( "}\n" );
}
/**
* Emit the start of a graph. Override this method to change the format of
* the start of a graph.
* @param stream
* the stream to emit the graph start to.
* @throws IOException
* if there is an error in emitting the graph start.
*/
protected void emitGraphStart( Appendable stream ) throws IOException
{
stream.append( "digraph Neo {\n" );
emitHeaders(stream);
}
protected void emitHeaders( Appendable stream ) throws IOException
{
if ( configuration != null )
{
configuration.emitHeader( stream );
}
stream.append( " node [\n" );
if ( configuration != null )
{
configuration.emitHeaderNode( stream );
}
else
{
header().emitNode( stream );
}
stream.append( " ]\n" );
stream.append( " edge [\n" );
if ( configuration != null )
{
configuration.emitHeaderEdge( stream );
}
else
{
header().emitEdge( stream );
}
stream.append( " ]\n" );
}
final NodeStyle nodeStyle;
final RelationshipStyle edgeStyle;
private final DefaultStyleConfiguration configuration;
private static volatile Header header;
GraphStyle getSubgraphStyle( final String subgraphName )
{
return new GraphStyle( nodeStyle, edgeStyle )
{
@Override
protected void emitGraphStart( Appendable stream ) throws IOException
{
stream.append( String.format( " subgraph cluster_%s {", subgraphName ) );
}
@Override
protected void emitGraphEnd( Appendable stream ) throws IOException
{
stream.append( String.format( " label = \"%s\"\n }\n", subgraphName ) );
}
};
}
static Header header()
{
Header instance = header;
if ( instance == null )
{
synchronized ( GraphStyle.class )
{
instance = header;
if ( instance == null )
{
header = instance = new Header();
}
}
}
return instance;
}
static final class Header
{
private Header()
{
String prefix = getClass().getPackage().getName() + ".";
String nodePrefix = prefix + "node.";
String relPrefix = prefix + "relationship.";
Properties properties = System.getProperties();
for ( Object obj : properties.keySet() )
{
try
{
String property = ( String ) obj;
if ( property.startsWith( nodePrefix ) )
{
nodeHeader.put( property
.substring( nodePrefix.length() ),
( String ) properties.get( property ) );
}
else if ( property.startsWith( relPrefix ) )
{
edgeHeader.put(
property.substring( relPrefix.length() ),
( String ) properties.get( property ) );
}
}
catch ( ClassCastException cce )
{
continue;
}
}
assertMember( nodeHeader, properties, prefix, "fontname",
"Bitstream Vera Sans" );
assertMember( nodeHeader, properties, prefix, "fontsize", "8" );
assertMember( edgeHeader, properties, prefix, "fontname",
"Bitstream Vera Sans" );
assertMember( edgeHeader, properties, prefix, "fontsize", "8" );
nodeHeader.put( "shape", "Mrecord" );
}
final Map<String, String> nodeHeader = new HashMap<String, String>();
final Map<String, String> edgeHeader = new HashMap<String, String>();
final Map<String, String> graphHeader = new HashMap<String, String>();
private void assertMember( Map<String, String> header,
Properties properties, String prefix, String key, String def )
{
if ( !header.containsKey( key ) )
{
header.put( key, properties.getProperty( prefix + key, def ) );
}
}
private void emitNode( Appendable stream ) throws IOException
{
emitHeader( stream, nodeHeader );
}
private void emitEdge( Appendable stream ) throws IOException
{
emitHeader( stream, edgeHeader );
}
}
static void emitHeader( Appendable stream, Map<String, String> header )
throws IOException
{
for ( String key : header.keySet() )
{
stream.append( " " + key + " = \"" + header.get( key ) + "\"\n" );
}
}
}
| false
|
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_GraphStyle.java
|
1,877
|
class DefaultStyleConfiguration implements StyleConfiguration
{
boolean displayRelationshipLabel = true;
DefaultStyleConfiguration( StyleParameter... parameters )
{
this.nodeHeader = new HashMap<String, String>(
GraphStyle.header().nodeHeader );
this.edgeHeader = new HashMap<String, String>(
GraphStyle.header().edgeHeader );
this.header = new HashMap<String, String>(
GraphStyle.header().graphHeader );
for ( StyleParameter parameter : parameters )
{
parameter.configure( this );
}
}
public String escapeLabel( String label )
{
label = label.replace( "\\", "\\\\" );
label = label.replace( "\"", "\\\"" );
label = label.replace( "'", "\\'" );
label = label.replace( "\n", "\\n" );
label = label.replace( "<", "\\<" );
label = label.replace( ">", "\\>" );
label = label.replace( "[", "\\[" );
label = label.replace( "]", "\\]" );
label = label.replace( "{", "\\{" );
label = label.replace( "}", "\\}" );
label = label.replace( "|", "\\|" );
return label;
}
private final Map<String, String> header;
private final Map<String, String> nodeHeader;
private final Map<String, String> edgeHeader;
private final Map<String, ParameterGetter<? super Node>> nodeParams = new HashMap<String, ParameterGetter<? super Node>>();
private final Map<String, ParameterGetter<? super Relationship>> edgeParams = new HashMap<String, ParameterGetter<? super Relationship>>();
private PropertyFilter nodeFilter = null;
private PropertyFilter edgeFilter = null;
private TitleGetter<? super Node> nodeTitle = null;
private TitleGetter<? super Relationship> edgeTitle = null;
private PropertyFormatter nodeFormat = null;
private PropertyFormatter edgeFormat = null;
private Predicate<Relationship> reversedRelationshipOrder = null;
boolean reverseOrder( Relationship edge )
{
return reversedRelationshipOrder != null && reversedRelationshipOrder.accept( edge );
}
void emitHeader( Appendable stream ) throws IOException
{
GraphStyle.emitHeader( stream, header );
}
void emitHeaderNode( Appendable stream ) throws IOException
{
GraphStyle.emitHeader( stream, nodeHeader );
}
void emitHeaderEdge( Appendable stream ) throws IOException
{
GraphStyle.emitHeader( stream, edgeHeader );
}
void emit( Node node, Appendable stream ) throws IOException
{
emit( node, nodeParams, stream );
}
void emit( Relationship edge, Appendable stream ) throws IOException
{
emit( edge, edgeParams, stream );
}
private <C extends PropertyContainer> void emit( C container,
Map<String, ParameterGetter<? super C>> params, Appendable stream )
throws IOException
{
for ( String key : params.keySet() )
{
String value = params.get( key ).getParameterValue( container, key );
if ( value != null )
{
stream.append( " " + key + " = \"" + value + "\"\n" );
}
}
}
String getTitle( Node node )
{
if ( nodeTitle != null )
{
return nodeTitle.getTitle( node );
}
else
{
return node.toString();
}
}
String getTitle( Relationship edge )
{
if ( edgeTitle != null )
{
return edgeTitle.getTitle( edge );
}
else
{
return edge.getType().name();
}
}
boolean acceptNodeProperty( String key )
{
if ( nodeFilter != null )
{
return nodeFilter.acceptProperty( key );
}
else
{
return true;
}
}
boolean acceptEdgeProperty( String key )
{
if ( edgeFilter != null )
{
return edgeFilter.acceptProperty( key );
}
else
{
return true;
}
}
void emitNodeProperty( Appendable stream, String key, PropertyType type,
Object value ) throws IOException
{
if ( nodeFormat != null )
{
stream.append( nodeFormat.format( key, type, value ) + "\\l" );
}
else
{
stream.append( PropertyType.STRING.format(key) + " = " + PropertyType.format( value ) + " : "
+ type.typeName + "\\l" );
}
}
void emitRelationshipProperty( Appendable stream, String key,
PropertyType type, Object value ) throws IOException
{
if ( edgeFormat != null )
{
stream.append( edgeFormat.format( key, type, value ) + "\\l" );
}
else
{
stream.append( PropertyType.STRING.format(key) + " = " + PropertyType.format( value ) + " : "
+ type.typeName + "\\l" );
}
}
public void setRelationshipReverseOrderPredicate( Predicate<Relationship> reversed )
{
reversedRelationshipOrder = reversed;
}
public void setGraphProperty( String property, String value )
{
header.put( property, value );
}
public void setDefaultNodeProperty( String property, String value )
{
nodeHeader.put( property, value );
}
public void setDefaultRelationshipProperty( String property, String value )
{
edgeHeader.put( property, value );
}
public void displayRelationshipLabel( boolean on )
{
displayRelationshipLabel = on;
}
public void setNodeParameterGetter( String key,
ParameterGetter<? super Node> getter )
{
nodeParams.put( key, getter );
}
public void setNodePropertyFilter( PropertyFilter filter )
{
nodeFilter = filter;
}
public void setNodeTitleGetter( TitleGetter<? super Node> getter )
{
nodeTitle = getter;
}
public void setRelationshipParameterGetter( String key,
ParameterGetter<? super Relationship> getter )
{
edgeParams.put( key, getter );
}
public void setRelationshipPropertyFilter( PropertyFilter filter )
{
edgeFilter = filter;
}
public void setRelationshipTitleGetter(
TitleGetter<? super Relationship> getter )
{
edgeTitle = getter;
}
public void setNodePropertyFomatter( PropertyFormatter format )
{
this.nodeFormat = format;
}
public void setRelationshipPropertyFomatter( PropertyFormatter format )
{
this.edgeFormat = format;
}
}
| false
|
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_DefaultStyleConfiguration.java
|
1,878
|
class DefaultRelationshipStyle implements RelationshipStyle
{
private final DefaultStyleConfiguration config;
DefaultRelationshipStyle( DefaultStyleConfiguration configuration )
{
this.config = configuration;
}
public void emitRelationshipStart( Appendable stream, Relationship relationship )
throws IOException
{
Node start = relationship.getStartNode(), end = relationship.getEndNode();
boolean reversed = config.reverseOrder( relationship );
long startId = start.getId(), endId = end.getId();
if ( reversed )
{
long tmp = startId;
startId = endId;
endId = tmp;
}
stream.append( " N" + startId + " -> N" + endId + " [\n" );
config.emit( relationship, stream );
if ( reversed ) stream.append( " dir = back\n" );
if ( config.displayRelationshipLabel )
{
stream.append( " label = \"" + config.escapeLabel(config.getTitle( relationship )) + "\\n" );
}
}
public void emitEnd( Appendable stream ) throws IOException
{
stream.append( config.displayRelationshipLabel ? "\"\n ]\n" : " ]\n" );
}
public void emitProperty( Appendable stream, String key, Object value ) throws IOException
{
if ( config.displayRelationshipLabel && config.acceptEdgeProperty( key ) )
{
PropertyType type = PropertyType.getTypeOf( value );
config.emitRelationshipProperty( stream, key, type, value );
}
}
}
| false
|
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_DefaultRelationshipStyle.java
|
1,879
|
class DefaultNodeStyle implements NodeStyle
{
protected final DefaultStyleConfiguration config;
DefaultNodeStyle( DefaultStyleConfiguration configuration )
{
this.config = configuration;
}
@Override
public void emitNodeStart( Appendable stream, Node node )
throws IOException
{
stream.append( " N" + node.getId() + " [\n" );
config.emit( node, stream );
stream.append( " label = \"{"
+ config.escapeLabel( config.getTitle( node ) ) );
Iterator<Label> labels = node.getLabels().iterator();
if ( labels.hasNext() )
{
if ( labels.hasNext() )
{
stream.append( ": " );
while ( labels.hasNext() )
{
stream.append( labels.next()
.name() );
if ( labels.hasNext() )
{
stream.append( ", " );
}
}
}
stream.append( "|" );
}
}
@Override
public void emitEnd( Appendable stream ) throws IOException
{
stream.append( "}\"\n ]\n" );
}
@Override
public void emitProperty( Appendable stream, String key, Object value )
throws IOException
{
if ( config.acceptNodeProperty( key ) )
{
PropertyType type = PropertyType.getTypeOf( value );
config.emitNodeProperty( stream, key, type, value );
}
}
}
| false
|
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_DefaultNodeStyle.java
|
1,880
|
private static class PatternParser
{
private final String pattern;
PatternParser( String pattern )
{
this.pattern = pattern;
}
String parse( PropertyContainer container )
{
StringBuilder result = new StringBuilder();
for ( int pos = 0; pos < pattern.length(); )
{
char cur = pattern.charAt( pos++ );
if ( cur == '@' )
{
String key = untilNonAlfa( pos );
result.append( getSpecial( key, container ) );
pos += key.length();
}
else if ( cur == '$' )
{
String key;
if ( pattern.charAt( pos ) == '{' )
{
key = pattern.substring( ++pos, pattern.indexOf( '}',
pos++ ) );
}
else
{
key = untilNonAlfa( pos );
}
pos += pattern.length();
result.append( container.getProperty( key ) );
}
else if ( cur == '\\' )
{
result.append( pattern.charAt( pos++ ) );
}
else
{
result.append( cur );
}
}
return result.toString();
}
private String untilNonAlfa( int start )
{
int end = start;
while ( end < pattern.length() && Character.isLetter( pattern.charAt( end ) ) )
{
end++;
}
return pattern.substring( start, end );
}
private String getSpecial( String attribute, PropertyContainer container )
{
if ( attribute.equals( "id" ) )
{
if ( container instanceof Node )
{
return "" + ( (Node) container ).getId();
}
else if ( container instanceof Relationship )
{
return "" + ( (Relationship) container ).getId();
}
}
else if ( attribute.equals( "type" ) )
{
if ( container instanceof Relationship )
{
return ( (Relationship) container ).getType().name();
}
}
return "@" + attribute;
}
}
| false
|
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_ConfigurationParser.java
|
1,881
|
private static class LineIterator extends PrefetchingIterator<String>
{
private final BufferedReader reader;
public LineIterator( BufferedReader reader )
{
this.reader = reader;
}
public LineIterator( File file )
{
this( fileReader( file ) );
}
private static BufferedReader fileReader( File file )
{
try
{
return new BufferedReader( new InputStreamReader( new FileInputStream( file ), "UTF-8" ) );
}
catch ( FileNotFoundException e )
{
return null;
}
catch ( UnsupportedEncodingException e )
{
throw new RuntimeException( e );
}
}
@Override
protected String fetchNextOrNull()
{
try
{
return reader.readLine();
}
catch ( Exception e )
{
return null;
}
}
}
| false
|
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_ConfigurationParser.java
|
1,882
|
styles.add( new StyleParameter.NodePropertyFilter() {
public boolean acceptProperty(String key) {
return Arrays.asList(nodePropertiesString.split(",")).contains(key);
}
});
| false
|
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_ConfigurationParser.java
|
1,883
|
{
public String getTitle( Relationship container )
{
return parser.parse( container );
}
} );
| false
|
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_ConfigurationParser.java
|
1,884
|
{
public String getTitle( Node container )
{
return parser.parse( container );
}
} );
| false
|
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_ConfigurationParser.java
|
1,885
|
public class ConfigurationParser
{
@SuppressWarnings( "unchecked" )
public ConfigurationParser( File configFile, String... format )
{
this( IteratorUtil.asIterable( new CombiningIterator<String>( Arrays.asList(
new LineIterator( configFile ), new ArrayIterator<String>( format ) ) ) ) );
}
public ConfigurationParser( String... format )
{
this( IteratorUtil.asIterable( new ArrayIterator<String>( format ) ) );
}
public ConfigurationParser( Iterable<String> format )
{
Class<? extends ConfigurationParser> type = getClass();
for ( String spec : format )
{
String[] parts = spec.split( "=", 2 );
String name = parts[0];
String[] args = null;
Method method;
Throwable error = null;
try
{
if ( parts.length == 1 )
{
method = type.getMethod( name, String[].class );
}
else
{
try
{
method = type.getMethod( name, String.class );
args = new String[] { parts[1] };
}
catch ( NoSuchMethodException nsm )
{
error = nsm; // use as a flag to know how to invoke
method = type.getMethod( name, String[].class );
args = parts[1].split( "," );
}
}
try
{
if ( error == null )
{
method.invoke( this, (Object[]) args );
}
else
{
error = null; // reset the flag use
method.invoke( this, (Object) args );
}
}
catch ( InvocationTargetException ex )
{
error = ex.getTargetException();
if ( error instanceof RuntimeException )
{
throw (RuntimeException) error;
}
}
catch ( Exception ex )
{
error = ex;
}
}
catch ( NoSuchMethodException nsm )
{
error = nsm;
}
if ( error != null )
{
throw new IllegalArgumentException( "Unknown parameter \""
+ name + "\"", error );
}
}
}
private final List<StyleParameter> styles = new ArrayList<StyleParameter>();
public final StyleParameter[] styles( StyleParameter... params )
{
if ( params == null ) params = new StyleParameter[0];
StyleParameter[] result = styles.toArray( new StyleParameter[styles.size() + params.length] );
System.arraycopy( params, 0, result, styles.size(), params.length );
return result;
}
public void nodeTitle( String pattern )
{
final PatternParser parser = new PatternParser( pattern );
styles.add( new StyleParameter.NodeTitle()
{
public String getTitle( Node container )
{
return parser.parse( container );
}
} );
}
public void relationshipTitle( String pattern )
{
final PatternParser parser = new PatternParser( pattern );
styles.add( new StyleParameter.RelationshipTitle()
{
public String getTitle( Relationship container )
{
return parser.parse( container );
}
} );
}
public void nodePropertyFilter( String nodeProperties )
{
final String nodePropertiesString = nodeProperties;
styles.add( new StyleParameter.NodePropertyFilter() {
public boolean acceptProperty(String key) {
return Arrays.asList(nodePropertiesString.split(",")).contains(key);
}
});
}
public void reverseOrder( String... typeNames )
{
if (typeNames== null || typeNames.length == 0) return;
RelationshipType[] types = new RelationshipType[typeNames.length];
for ( int i = 0; i < typeNames.length; i++ )
{
types[i] = DynamicRelationshipType.withName( typeNames[i] );
}
styles.add( new StyleParameter.ReverseOrderRelationshipTypes( types ) );
}
private static class PatternParser
{
private final String pattern;
PatternParser( String pattern )
{
this.pattern = pattern;
}
String parse( PropertyContainer container )
{
StringBuilder result = new StringBuilder();
for ( int pos = 0; pos < pattern.length(); )
{
char cur = pattern.charAt( pos++ );
if ( cur == '@' )
{
String key = untilNonAlfa( pos );
result.append( getSpecial( key, container ) );
pos += key.length();
}
else if ( cur == '$' )
{
String key;
if ( pattern.charAt( pos ) == '{' )
{
key = pattern.substring( ++pos, pattern.indexOf( '}',
pos++ ) );
}
else
{
key = untilNonAlfa( pos );
}
pos += pattern.length();
result.append( container.getProperty( key ) );
}
else if ( cur == '\\' )
{
result.append( pattern.charAt( pos++ ) );
}
else
{
result.append( cur );
}
}
return result.toString();
}
private String untilNonAlfa( int start )
{
int end = start;
while ( end < pattern.length() && Character.isLetter( pattern.charAt( end ) ) )
{
end++;
}
return pattern.substring( start, end );
}
private String getSpecial( String attribute, PropertyContainer container )
{
if ( attribute.equals( "id" ) )
{
if ( container instanceof Node )
{
return "" + ( (Node) container ).getId();
}
else if ( container instanceof Relationship )
{
return "" + ( (Relationship) container ).getId();
}
}
else if ( attribute.equals( "type" ) )
{
if ( container instanceof Relationship )
{
return ( (Relationship) container ).getType().name();
}
}
return "@" + attribute;
}
}
private static class LineIterator extends PrefetchingIterator<String>
{
private final BufferedReader reader;
public LineIterator( BufferedReader reader )
{
this.reader = reader;
}
public LineIterator( File file )
{
this( fileReader( file ) );
}
private static BufferedReader fileReader( File file )
{
try
{
return new BufferedReader( new InputStreamReader( new FileInputStream( file ), "UTF-8" ) );
}
catch ( FileNotFoundException e )
{
return null;
}
catch ( UnsupportedEncodingException e )
{
throw new RuntimeException( e );
}
}
@Override
protected String fetchNextOrNull()
{
try
{
return reader.readLine();
}
catch ( Exception e )
{
return null;
}
}
}
}
| false
|
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_ConfigurationParser.java
|
1,886
|
public class AsciidocHelperTest
{
@Test
public void test()
{
String cypher = "start n=node(0) " +
"match " +
"x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, " +
"x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, " +
"x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n, x-n " +
"return n, x";
String snippet = AsciidocHelper.createCypherSnippet( cypher );
assertTrue(snippet.contains( "n,\n" ));
}
@Test
public void shouldBreakAtTheRightSpotWithOnMatch()
{
// given
String cypher = "merge (a)\non match set a.foo = 2";
//when
String snippet = AsciidocHelper.createCypherSnippet(cypher);
//then
assertEquals(
"[source,cypher]\n" +
"----\n" +
"MERGE (a)\n" +
"ON MATCH SET a.foo = 2\n" +
"----\n", snippet);
}
@Test
public void testUpcasingLabels() {
String queryString = "create n label :Person {} on tail";
String snippet = AsciidocHelper.createCypherSnippet( queryString );
assertTrue( snippet.contains( "LABEL" ) );
assertTrue( snippet.contains( "ON" ) );
assertFalse( snippet.contains( ":PersON" ) );
}
}
| false
|
community_graphviz_src_test_java_org_neo4j_visualization_graphviz_AsciidocHelperTest.java
|
1,887
|
public class AsciiDocStyle extends GraphStyle
{
static final Simple SIMPLE_PROPERTY_STYLE = StyleParameter.Simple.PROPERTY_AS_KEY_EQUALS_VALUE;
static final DefaultStyleConfiguration PLAIN_STYLE = new DefaultStyleConfiguration(
SIMPLE_PROPERTY_STYLE );
public AsciiDocStyle()
{
super();
}
AsciiDocStyle( StyleParameter... parameters )
{
super( parameters );
}
public AsciiDocStyle( NodeStyle nodeStyle, RelationshipStyle edgeStyle )
{
super( nodeStyle, edgeStyle );
}
@Override
protected void emitGraphStart( Appendable stream ) throws IOException
{
}
@Override
protected void emitGraphEnd( Appendable stream ) throws IOException
{
}
public static AsciiDocStyle withAutomaticRelationshipTypeColors()
{
return new AsciiDocStyle( new DefaultNodeStyle( PLAIN_STYLE ),
new DefaultRelationshipStyle( new DefaultStyleConfiguration(
AsciiDocStyle.SIMPLE_PROPERTY_STYLE,
new AutoRelationshipTypeColor() ) ) );
}
}
| false
|
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_AsciiDocStyle.java
|
1,888
|
public class AsciiDocSimpleStyle extends AsciiDocStyle
{
private AsciiDocSimpleStyle()
{
this( false, true );
}
private AsciiDocSimpleStyle( NodeStyle nodeStyle,
RelationshipStyle edgeStyle )
{
super( nodeStyle, edgeStyle );
}
private AsciiDocSimpleStyle( boolean autoColoredNodes,
boolean autoColoredRelationships )
{
super( new SimpleNodeStyle( defaultNodeConfig( autoColoredNodes ) ),
new DefaultRelationshipStyle(
defaultRelationshipConfig( autoColoredRelationships ) ) );
}
private AsciiDocSimpleStyle(
ColorMapper<RelationshipType> relationshipTypeColors,
boolean autoColoredNodes )
{
super(
new SimpleNodeStyle( defaultNodeConfig( autoColoredNodes ) ),
new DefaultRelationshipStyle(
new DefaultStyleConfiguration(
AsciiDocStyle.SIMPLE_PROPERTY_STYLE,
new AutoRelationshipTypeColor(
relationshipTypeColors ) ) ) );
}
private AsciiDocSimpleStyle( boolean autoColoredRelationships,
ColorMapper<Node> nodeColors )
{
super( new SimpleNodeStyle( new DefaultStyleConfiguration(
new AutoNodeColor( nodeColors ) ) ),
new DefaultRelationshipStyle(
defaultRelationshipConfig( autoColoredRelationships ) ) );
}
private AsciiDocSimpleStyle( ColorMapper<Node> nodeColors,
ColorMapper<RelationshipType> relationshipTypeColors )
{
super(
new SimpleNodeStyle( new DefaultStyleConfiguration(
new AutoNodeColor( nodeColors ) ) ),
new DefaultRelationshipStyle(
new DefaultStyleConfiguration(
AsciiDocStyle.SIMPLE_PROPERTY_STYLE,
new AutoRelationshipTypeColor(
relationshipTypeColors ) ) ) );
}
private static DefaultStyleConfiguration defaultRelationshipConfig(
boolean autoColoredRelationships )
{
if ( autoColoredRelationships )
{
return new DefaultStyleConfiguration(
AsciiDocStyle.SIMPLE_PROPERTY_STYLE,
new AutoRelationshipTypeColor() );
}
else
{
return AsciiDocStyle.PLAIN_STYLE;
}
}
private static DefaultStyleConfiguration defaultNodeConfig(
boolean autoColoredNodes )
{
if ( autoColoredNodes )
{
return new DefaultStyleConfiguration(
AsciiDocStyle.SIMPLE_PROPERTY_STYLE,
new AutoNodeColor() );
}
else
{
return AsciiDocStyle.PLAIN_STYLE;
}
}
public static AsciiDocSimpleStyle withoutColors()
{
return new AsciiDocSimpleStyle( false, false );
}
public static AsciiDocSimpleStyle withAutomaticRelationshipTypeColors()
{
return new AsciiDocSimpleStyle( false, true );
}
public static AsciiDocSimpleStyle withAutomaticNodeColors()
{
return new AsciiDocSimpleStyle( true, false );
}
public static AsciiDocSimpleStyle withAutomaticNodeAndRelationshipTypeColors()
{
return new AsciiDocSimpleStyle( true, true );
}
public static AsciiDocSimpleStyle withPredefinedRelationshipTypeColors(
ColorMapper<RelationshipType> relationshipTypeColors )
{
return new AsciiDocSimpleStyle( relationshipTypeColors, false );
}
public static AsciiDocSimpleStyle withAudomaticNodeAndPredefinedRelationshipTypeColors(
ColorMapper<RelationshipType> relationshipTypeColors )
{
return new AsciiDocSimpleStyle( relationshipTypeColors, true );
}
public static AsciiDocSimpleStyle withPredefinedNodeColors(
ColorMapper<Node> nodeColors )
{
return new AsciiDocSimpleStyle( false, nodeColors );
}
public static AsciiDocSimpleStyle withPredefinedNodeColorsAndAutomaticRelationshipTypeColors(
ColorMapper<Node> nodeColors )
{
return new AsciiDocSimpleStyle( true, nodeColors );
}
public static AsciiDocSimpleStyle withPredefinedNodeAndRelationshipTypeColors(
ColorMapper<Node> nodeColors,
ColorMapper<RelationshipType> relationshipTypeColors )
{
return new AsciiDocSimpleStyle( nodeColors, relationshipTypeColors );
}
public static AsciiDocSimpleStyle withPredefinedNodeAndRelationshipStyles(
NodeStyle nodeStyle, RelationshipStyle edgeStyle )
{
return new AsciiDocSimpleStyle( nodeStyle, edgeStyle );
}
}
| false
|
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_AsciiDocSimpleStyle.java
|
1,889
|
public class AsciidocHelper
{
/**
* Cut to max 123 chars for PDF layout compliance. Or even less, for
* readability.
*/
private static final int MAX_CHARS_PER_LINE = 100;
/**
* Cut text message line length for readability.
*/
private static final int MAX_TEXT_LINE_LENGTH = 80;
/**
* Characters to remove from the title.
*/
private static final String ILLEGAL_STRINGS = "[:\\(\\)\t;&/\\\\]";
public static String createGraphViz( String title,
GraphDatabaseService graph, String identifier )
{
return createGraphViz( title, graph, identifier,
AsciiDocSimpleStyle.withAutomaticRelationshipTypeColors() );
}
public static String createGraphViz( String title,
GraphDatabaseService graph, String identifier,
String graphvizOptions )
{
return createGraphViz( title, graph, identifier,
AsciiDocSimpleStyle.withAutomaticRelationshipTypeColors(),
graphvizOptions );
}
public static String createGraphVizWithNodeId( String title,
GraphDatabaseService graph, String identifier )
{
return createGraphViz( title, graph, identifier,
AsciiDocStyle.withAutomaticRelationshipTypeColors() );
}
public static String createGraphVizWithNodeId( String title,
GraphDatabaseService graph, String identifier,
String graphvizOptions )
{
return createGraphViz( title, graph, identifier,
AsciiDocStyle.withAutomaticRelationshipTypeColors(),
graphvizOptions );
}
public static String createGraphVizDeletingReferenceNode( String title,
GraphDatabaseService graph, String identifier )
{
return createGraphVizDeletingReferenceNode( title, graph, identifier,
"" );
}
public static String createGraphVizDeletingReferenceNode( String title,
GraphDatabaseService graph, String identifier,
String graphvizOptions )
{
return createGraphViz( title, graph, identifier,
AsciiDocSimpleStyle.withAutomaticRelationshipTypeColors(),
graphvizOptions );
}
public static String createGraphVizWithNodeIdDeletingReferenceNode(
String title, GraphDatabaseService graph, String identifier )
{
return createGraphVizWithNodeIdDeletingReferenceNode( title, graph,
identifier, "" );
}
public static String createGraphVizWithNodeIdDeletingReferenceNode(
String title, GraphDatabaseService graph, String identifier,
String graphvizOptions )
{
return createGraphViz( title, graph, identifier,
AsciiDocStyle.withAutomaticRelationshipTypeColors(),
graphvizOptions );
}
/**
* Create graphviz output using a {@link GraphStyle) which is implemented by
* {@link AsciiDocSimpleStyle} and {@link AsciiDocStyle}.
* {@link AsciiDocSimpleStyle} provides different customization options for
* coloring.
*/
public static String createGraphViz( String title,
GraphDatabaseService graph, String identifier, GraphStyle graphStyle )
{
return createGraphViz( title, graph, identifier, graphStyle, "" );
}
public static String createGraphViz( String title,
GraphDatabaseService graph, String identifier,
GraphStyle graphStyle, String graphvizOptions )
{
try ( Transaction tx = graph.beginTx() )
{
GraphvizWriter writer = new GraphvizWriter( graphStyle );
ByteArrayOutputStream out = new ByteArrayOutputStream();
try
{
writer.emit( out, Walker.fullGraph( graph ) );
}
catch ( IOException e )
{
e.printStackTrace();
}
String safeTitle = title.replaceAll( ILLEGAL_STRINGS, "" );
tx.success();
try
{
return "." + title + "\n[\"dot\", \""
+ (safeTitle + "-" + identifier).replace( " ", "-" )
+ ".svg\", \"neoviz\", \"" + graphvizOptions + "\"]\n"
+ "----\n" + out.toString( "UTF-8" ) + "----\n";
}
catch ( UnsupportedEncodingException e )
{
throw new RuntimeException( e );
}
}
}
public static String createOutputSnippet( final String output )
{
return "[source]\n----\n" + output + "\n----\n";
}
public static String createQueryResultSnippet( final String output )
{
return "[queryresult]\n----\n" + output
+ (output.endsWith( "\n" ) ? "" : "\n") + "----\n";
}
public static String createQueryFailureSnippet( final String output )
{
return "[source]\n----\n" + wrapText( output ) + "\n----\n";
}
private static String wrapText( final String text )
{
return wrap( text, MAX_TEXT_LINE_LENGTH, " ", "\n" );
}
static String wrapQuery( final String query )
{
String wrapped = wrap( query, MAX_CHARS_PER_LINE, ", ", ",\n " );
wrapped = wrap( wrapped, MAX_CHARS_PER_LINE, "),(", "),\n (" );
return wrap( wrapped, MAX_CHARS_PER_LINE, " ", "\n " );
}
private static String wrap( final String text, final int maxChars, final String search, final String replace )
{
StringBuffer out = new StringBuffer( text.length() + 10 * replace.length() );
String pattern = Pattern.quote( search );
for ( String line : text.trim()
.split( "\n" ) )
{
if ( line.length() < maxChars )
{
out.append( line )
.append( '\n' );
}
else
{
int currentLength = 0;
for ( String word : line.split( pattern ) )
{
if ( currentLength + word.length() > maxChars )
{
if ( currentLength > 0 )
{
out.append( replace );
}
out.append( word );
currentLength = replace.length() + word.length();
}
else
{
if ( currentLength != 0 )
{
out.append( search );
currentLength += search.length();
}
out.append( word );
currentLength += word.length();
}
}
out.append( '\n' );
}
}
return out.substring( 0, out.length() - 1 );
}
public static String createCypherSnippet( final String query )
{
String[] keywordsToBreakOn = new String[]{"start", "create", "unique", "set", "delete", "foreach",
"match", "where", "with", "return", "skip", "limit", "order by", "asc", "ascending",
"desc", "descending", "create", "remove", "drop", "using", "merge", "assert", "constraint"};
String[] unbreakableKeywords = new String[]{"label", "values", "on", "index"};
return createLanguageSnippet( query, "cypher", keywordsToBreakOn, unbreakableKeywords );
}
public static String createSqlSnippet( final String query )
{
String[] keywordsToBreakOn = new String[]{"select", "from", "where",
"skip", "limit", "order by", "asc", "ascending", "desc",
"descending", "join", "group by"};
String[] unbreakableKeywords = new String[]{};
return createLanguageSnippet( query, "sql", keywordsToBreakOn, unbreakableKeywords );
}
private static String createLanguageSnippet( String query,
String language,
String[] keywordsToBreakOn,
String[] unbreakableKeywords )
{
// This is not something I'm proud of. This should be done in Cypher by the parser.
// For now, learn to live with it.
String formattedQuery;
if ( "cypher".equals( language ) && query.contains( "merge" ) )
{
formattedQuery = uppercaseKeywords( query, keywordsToBreakOn );
formattedQuery = uppercaseKeywords( formattedQuery, unbreakableKeywords );
} else
{
formattedQuery = breakOnKeywords( query, keywordsToBreakOn );
formattedQuery = uppercaseKeywords( formattedQuery, unbreakableKeywords );
}
String result = createAsciiDocSnippet(language, formattedQuery);
return limitChars( result );
}
public static String createCypherSnippetFromPreformattedQuery( final String formattedQuery )
{
return format( "[source,%s]\n----\n%s%s----\n", "cypher", wrapQuery( formattedQuery ),
formattedQuery.endsWith( "\n" ) ? "" : "\n" );
}
public static String createAsciiDocSnippet(String language, String formattedQuery)
{
return format("[source,%s]\n----\n%s%s----\n",
language, formattedQuery, formattedQuery.endsWith("\n") ? "" : "\n");
}
private static String breakOnKeywords( String query, String[] keywordsToBreakOn )
{
String result = query;
for ( String keyword : keywordsToBreakOn )
{
String upperKeyword = keyword.toUpperCase();
result = ucaseIfFirstInLine( result, keyword, upperKeyword );
result = result.
replace( " " + upperKeyword + " ", "\n" + upperKeyword + " " );
}
return result;
}
private static String ucaseIfFirstInLine( String result, String keyword, String upperKeyword )
{
if ( result.length() > keyword.length() && result.startsWith( keyword + " " ) )
{
result = upperKeyword + " " + result.substring( keyword.length() + 1 );
}
return result.replace( "\n" + keyword, "\n" + upperKeyword );
}
private static String uppercaseKeywords( String query, String[] uppercaseKeywords )
{
String result = query;
for ( String keyword : uppercaseKeywords )
{
String upperKeyword = keyword.toUpperCase();
result = ucaseIfFirstInLine( result, keyword, upperKeyword );
result = result.
replace( " " + keyword + " ", " " + upperKeyword + " " );
}
return result;
}
private static String limitChars( String result )
{
String[] lines = result.split( "\n" );
String finalRes = "";
for ( String line : lines )
{
line = line.trim();
if ( line.length() > MAX_CHARS_PER_LINE )
{
line = line.replaceAll( ", ", ",\n " );
}
finalRes += line + "\n";
}
return finalRes;
}
}
| false
|
community_graphviz_src_main_java_org_neo4j_visualization_asciidoc_AsciidocHelper.java
|
1,890
|
public class Visualizer<E extends Throwable> implements Visitor<Void, E>
{
private final GraphRenderer<E> renderer;
private Set<Relationship> visitedRelationships = new HashSet<Relationship>();
private Set<Node> visitedNodes = new HashSet<Node>();
/**
* Creates a new visualizer.
* @param renderer
* An object capable of rendering the different parts of a graph.
*/
public Visualizer( GraphRenderer<E> renderer )
{
this.renderer = renderer;
}
public Void done() throws E
{
renderer.done();
return null;
}
public void visitNode( Node node ) throws E
{
if ( visitedNodes.add( node ) )
{
renderProperties( renderer.renderNode( node ), node );
}
}
public void visitRelationship( Relationship relationship ) throws E
{
if ( visitedRelationships.add( relationship ) )
{
renderProperties( renderer.renderRelationship( relationship ),
relationship );
}
}
public Visitor<Void, E> visitSubgraph( String name ) throws E
{
return new Visualizer<E>( renderer.renderSubgraph( name ) );
}
private void renderProperties( PropertyRenderer<E> propertyRenderer,
PropertyContainer container ) throws E
{
for ( String key : container.getPropertyKeys() )
{
propertyRenderer.renderProperty( key, container.getProperty( key ) );
}
propertyRenderer.done();
}
}
| false
|
community_graphviz_src_main_java_org_neo4j_visualization_Visualizer.java
|
1,891
|
public final class GraphvizWriter
{
private final GraphStyle style;
/**
* Create a new Graphviz writer.
* @param configuration
* the style parameters determining how the style of the output
* of this writer.
*/
public GraphvizWriter( StyleParameter... configuration )
{
this( new GraphStyle( configuration ) );
}
public GraphvizWriter( GraphStyle style )
{
this.style = style;
}
/**
* Emit a graph to a file in graphviz format using this writer.
* @param dest
* the file to write the graph to.
* @param walker
* a walker that walks the graph to emit.
* @throws IOException
* if there is an error in outputting to the specified file.
*/
public void emit( File dest, Walker walker ) throws IOException
{
OutputStream stream = new FileOutputStream( dest );
emit( stream, walker );
stream.close();
}
/**
* Emit a graph to an output stream in graphviz format using this writer.
* @param outputStream
* the stream to write the graph to.
* @param walker
* a walker that walks the graph to emit.
* @throws IOException
* if there is an error in outputting to the specified stream.
*/
public void emit( OutputStream outputStream, Walker walker )
throws IOException
{
if ( outputStream instanceof PrintStream )
{
emit( walker, new GraphvizRenderer( style,
( PrintStream ) outputStream ) );
}
else
{
emit( walker, new GraphvizRenderer( style, new PrintStream( outputStream, true, "UTF-8" ) ) );
}
}
private void emit( Walker walker, GraphvizRenderer renderer )
throws IOException
{
walker.accept( new Visualizer<IOException>( renderer ) );
}
}
| false
|
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_GraphvizWriter.java
|
1,892
|
public class SimpleNodeStyle extends DefaultNodeStyle
{
boolean hasLabels = false;
SimpleNodeStyle( DefaultStyleConfiguration configuration )
{
super( configuration );
}
@Override
public void emitNodeStart( Appendable stream, Node node )
throws IOException
{
stream.append( " N" + node.getId() + " [\n" );
config.emit( node, stream );
stream.append( " label = \"" );
Iterator<Label> labels = node.getLabels().iterator();
hasLabels = labels.hasNext();
if ( hasLabels )
{
hasLabels = labels.hasNext();
if ( hasLabels )
{
stream.append( "{" );
while ( labels.hasNext() )
{
stream.append( labels.next()
.name() );
if ( labels.hasNext() )
{
stream.append( ", " );
}
}
stream.append( "|" );
}
}
}
@Override
public void emitEnd( Appendable stream ) throws IOException
{
if ( hasLabels )
{
stream.append( "}\"\n ]\n" );
}
else
{
stream.append( "\"\n ]\n" );
}
}
}
| false
|
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_SimpleNodeStyle.java
|
1,893
|
public abstract class SubgraphMappingWalker extends Walker
{
private final SubgraphMapper mapper;
protected SubgraphMappingWalker( SubgraphMapper mapper )
{
this.mapper = mapper;
}
private Map<String, Collection<Node>> subgraphs;
private Collection<Node> generic;
private Collection<Relationship> relationships;
private synchronized void initialize()
{
if ( subgraphs != null ) return;
Map<Node, String> mappings = new HashMap<Node, String>();
subgraphs = new HashMap<String, Collection<Node>>();
generic = new ArrayList<Node>();
for ( Node node : nodes() )
{
if ( mappings.containsKey( node ) ) continue;
String subgraph = subgraphFor( node );
if ( !subgraphs.containsKey( subgraph ) && subgraph != null )
{
subgraphs.put( subgraph, new ArrayList<Node>() );
}
mappings.put( node, subgraph );
}
relationships = new ArrayList<Relationship>();
for ( Relationship rel : relationships() )
{
if ( mappings.containsKey( rel.getStartNode() )
&& mappings.containsKey( rel.getEndNode() ) )
{
relationships.add( rel );
}
}
for ( Map.Entry<Node, String> e : mappings.entrySet() )
{
( e.getValue() == null ? generic : subgraphs.get( e.getValue() ) ).add( e.getKey() );
}
}
private String subgraphFor( Node node )
{
return mapper == null ? null : mapper.getSubgraphFor( node );
}
@Override
public final <R, E extends Throwable> R accept( Visitor<R, E> visitor ) throws E
{
initialize();
for ( Map.Entry<String, Collection<Node>> subgraph : subgraphs.entrySet() )
{
Visitor<R, E> subVisitor = visitor.visitSubgraph( subgraph.getKey() );
for ( Node node : subgraph.getValue() )
{
subVisitor.visitNode( node );
}
subVisitor.done();
}
for ( Node node : generic )
{
visitor.visitNode( node );
}
for ( Relationship relationship : relationships )
{
visitor.visitRelationship( relationship );
}
return visitor.done();
}
protected abstract Iterable<Node> nodes();
protected abstract Iterable<Relationship> relationships();
}
| false
|
community_graphviz_src_main_java_org_neo4j_visualization_SubgraphMapper.java
|
1,894
|
final class DefaultNodeProperty implements StyleParameter
{
private final String property;
private final String value;
/**
* Add a property to the general node configuration.
* @param property
* the property key.
* @param value
* the property value.
*/
public DefaultNodeProperty( String property, String value )
{
this.property = property;
this.value = value;
}
public final void configure( StyleConfiguration configuration )
{
configuration.setDefaultNodeProperty( property, value );
}
}
| false
|
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_StyleParameter.java
|
1,895
|
abstract class RelationshipTailLabel implements StyleParameter
{
public void configure( StyleConfiguration configuration )
{
configuration.setRelationshipParameterGetter( "taillabel",
new ParameterGetter<Relationship>()
{
public String getParameterValue( Relationship container,
String key )
{
return getTailLabel( container );
}
} );
}
/**
* Get the tail label for a relationship.
* @param relationship
* the relationship to get the tail label for.
* @return the tail label for the relationship.
*/
protected abstract String getTailLabel( Relationship relationship );
}
| false
|
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_StyleParameter.java
|
1,896
|
abstract class RelationshipPropertyFormat implements StyleParameter,
PropertyFormatter
{
public final void configure( StyleConfiguration configuration )
{
configuration.setRelationshipPropertyFomatter( this );
}
}
| false
|
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_StyleParameter.java
|
1,897
|
abstract class RelationshipPropertyFilter implements StyleParameter,
PropertyFilter
{
public final void configure( StyleConfiguration configuration )
{
configuration.setRelationshipPropertyFilter( this );
}
}
| false
|
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_StyleParameter.java
|
1,898
|
{
public String getParameterValue( Relationship container,
String key )
{
return getHeadLabel( container );
}
} );
| false
|
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_StyleParameter.java
|
1,899
|
abstract class RelationshipHeadLabel implements StyleParameter
{
public void configure( StyleConfiguration configuration )
{
configuration.setRelationshipParameterGetter( "headlabel",
new ParameterGetter<Relationship>()
{
public String getParameterValue( Relationship container,
String key )
{
return getHeadLabel( container );
}
} );
}
/**
* Get the head label for a relationship.
* @param relationship
* the relationship to get the head label for.
* @return the head label for the relationship.
*/
protected abstract String getHeadLabel( Relationship relationship );
}
| false
|
community_graphviz_src_main_java_org_neo4j_visualization_graphviz_StyleParameter.java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.