Unnamed: 0
int64
0
6.7k
func
stringlengths
12
89.6k
target
bool
2 classes
project
stringlengths
45
151
1,500
@SuppressWarnings( "serial" ) private static class TestingProcess extends SubProcess<Callable<String>, String> implements Callable<String> { private String message; private transient volatile boolean started = false; @Override protected void startup( String parameter ) { message = parameter; started = true; } public String call() throws Exception { while ( !started ) // because all calls are asynchronous Thread.sleep( 1 ); return message; } }
false
community_kernel_src_test_java_org_neo4j_metatest_SubProcessTest.java
1,501
private static class Timer { private final String name; private long time = 0; private Long start = null; private long items = 0; Timer( String name ) { this.name = name; } void start() { if ( start == null ) { start = System.nanoTime(); } } void stop() { if ( start != null ) { time += System.nanoTime() - start; } start = null; } void accept( Visitor visitor ) throws IOException { visitor.phaseTimingProgress( name, items, time ); } }
false
enterprise_enterprise-performance-tests_src_main_java_org_neo4j_perftest_enterprise_ccheck_TimingProgress.java
1,502
@Documented public class TestClasspath { @Test public void theTestClasspathShouldNotContainTheOriginalArtifacts() { for ( String lib : System.getProperty("java.class.path").split(":") ) { assertFalse( "test-jar on classpath: " + lib, lib.contains("test-jar") ); } } @Test public void canLoadSubProcess() throws Exception { assertNotNull( Class.forName( "org.neo4j.test.subprocess.SubProcess" ) ); } @Test public void canAccessJavadocThroughProcessedAnnotation() { Documented doc = getClass().getAnnotation( Documented.class ); assertNotNull( "accessing Documented annotation", doc ); assertEquals( "Tests the classpath for the tests", doc.value().trim() ); } }
false
testing-utils_src_test_java_org_neo4j_metatest_TestClasspath.java
1,503
public class ShellBootstrapTest { @Test public void shouldPickUpAllConfigOptions() throws Exception { // GIVEN String host = "test"; int port = 1234; String name = "my shell"; Config config = new Config( stringMap( ShellSettings.remote_shell_host.name(), host, ShellSettings.remote_shell_port.name(), valueOf( port ), ShellSettings.remote_shell_name.name(), name, ShellSettings.remote_shell_enabled.name(), TRUE.toString() ) ); GraphDatabaseShellServer server = mock( GraphDatabaseShellServer.class ); // WHEN server = new ShellBootstrap( config ).enable( server ); // THEN verify( server ).makeRemotelyAvailable( host, port, name ); } }
false
community_shell_src_test_java_org_neo4j_shell_impl_ShellBootstrapTest.java
1,504
public class SameJvmClient extends AbstractClient { private Output out; private ShellServer server; public SameJvmClient( Map<String, Serializable> initialSession, ShellServer server ) throws ShellException { this( initialSession, server, new SystemOutput() ); } /** * @param server the server to communicate with. */ public SameJvmClient( Map<String, Serializable> initialSession, ShellServer server, Output out ) throws ShellException { super( initialSession ); this.out = out; this.server = server; try { sayHi( server ); } catch ( RemoteException e ) { throw new RuntimeException( "Will not happen since this is in the same JVM", e ); } init(); updateTimeForMostRecentConnection(); } public Output getOutput() { return this.out; } public ShellServer getServer() { return this.server; } }
false
community_shell_src_main_java_org_neo4j_shell_impl_SameJvmClient.java
1,505
public class RmiLocation { private String host; private int port; private String name; private RmiLocation() { } private RmiLocation( String host, int port, String name ) { this.host = host; this.port = port; this.name = name; } /** * Creates a new RMI location instance. * @param url the RMI URL. * @return the {@link RmiLocation} instance for {@code url}. */ public static RmiLocation location( String url ) { int protocolIndex = url.indexOf( "://" ); int portIndex = url.lastIndexOf( ':' ); int nameIndex = url.indexOf( "/", portIndex ); String host = url.substring( protocolIndex + 3, portIndex ); int port = Integer.parseInt( url.substring( portIndex + 1, nameIndex ) ); String name = url.substring( nameIndex + 1 ); return location( host, port, name ); } /** * Creates a new RMI location instance. * @param host the RMI host, f.ex. "localhost". * @param port the RMI port. * @param name the RMI name, f.ex. "shell". * @return a new {@link RmiLocation} instance. */ public static RmiLocation location( String host, int port, String name ) { return new RmiLocation( host, port, name ); } /** * Creates a new RMI location instance. * @param data a map with data, should contain "host", "port" and "name". * See {@link #location(String, int, String)}. * @return a new {@link RmiLocation} instance. */ public static RmiLocation location( Map<String, Object> data ) { String host = ( String ) data.get( "host" ); Integer port = ( Integer ) data.get( "port" ); String name = ( String ) data.get( "name" ); return location( host, port, name ); } /** * @return the host of this RMI location. */ public String getHost() { return this.host; } /** * @return the port of this RMI location. */ public int getPort() { return this.port; } /** * @return the name of this RMI location. */ public String getName() { return this.name; } private static String getProtocol() { return "rmi://"; } /** * @return "short" URL, consisting of protocol, host and port, f.ex. * "rmi://localhost:8080". */ public String toShortUrl() { return getProtocol() + getHost() + ":" + getPort(); } /** * @return the full RMI URL, f.ex. * "rmi://localhost:8080/the/shellname". */ public String toUrl() { return getProtocol() + getHost() + ":" + getPort() + "/" + getName(); } /** * @return whether or not the RMI registry is created in this JVM for the * given port, see {@link #getPort()}. */ public boolean hasRegistry() { try { Naming.list( toShortUrl() ); return true; } catch ( RemoteException e ) { return false; } catch ( java.net.MalformedURLException e ) { return false; } } /** * Ensures that the RMI registry is created for this JVM instance and port, * see {@link #getPort()}. * @return the registry for the port. * @throws RemoteException RMI error. */ public Registry ensureRegistryCreated() throws RemoteException { try { Naming.list( toShortUrl() ); return LocateRegistry.getRegistry( getPort() ); } catch ( RemoteException e ) { return LocateRegistry.createRegistry( getPort() ); } catch ( java.net.MalformedURLException e ) { throw new RemoteException( "Malformed URL", e ); } } /** * Binds an object to the RMI location defined by this instance. * @param object the object to bind. * @throws RemoteException RMI error. */ public void bind( Remote object ) throws RemoteException { ensureRegistryCreated(); try { Naming.rebind( toUrl(), object ); } catch ( MalformedURLException e ) { throw new RemoteException( "Malformed URL", e ); } } /** * Unbinds an object from the RMI location defined by this instance. * @param object the object to bind. * @throws RemoteException RMI error. */ public void unbind( Remote object ) throws RemoteException { try { Naming.unbind( toUrl() ); UnicastRemoteObject.unexportObject( object, true ); } catch ( NotBoundException e ) { throw new RemoteException( "Not bound", e ); } catch ( MalformedURLException e ) { throw new RemoteException( "Malformed URL", e ); } } /** * @return whether or not there's an object bound to the RMI location * defined by this instance. */ public boolean isBound() { try { getBoundObject(); return true; } catch ( RemoteException e ) { return false; } } /** * @return the bound object for the RMI location defined by this instance. * @throws RemoteException if there's no object bound for the RMI location. */ public Remote getBoundObject() throws RemoteException { try { return Naming.lookup( toUrl() ); } catch ( NotBoundException e ) { throw new RemoteException( "Not bound", e ); } catch ( MalformedURLException e ) { throw new RemoteException( "Malformed URL", e ); } } }
false
community_shell_src_main_java_org_neo4j_shell_impl_RmiLocation.java
1,506
class RemotelyAvailableServer extends UnicastRemoteObject implements ShellServer { private final ShellServer actual; RemotelyAvailableServer( ShellServer actual ) throws RemoteException { super(); this.actual = actual; } @Override public String getName() throws RemoteException { return actual.getName(); } @Override public Response interpretLine( Serializable clientId, String line, Output out ) throws ShellException, RemoteException { return actual.interpretLine( clientId, line, out ); } @Override public Serializable interpretVariable( Serializable clientId, String key ) throws ShellException, RemoteException { return actual.interpretVariable( clientId, key ); } @Override public Welcome welcome( Map<String, Serializable> initialSession ) throws RemoteException, ShellException { return actual.welcome( initialSession ); } @Override public void leave( Serializable clientID ) throws RemoteException { actual.leave( clientID ); } @Override public void shutdown() throws RemoteException { try { unexportObject( this, true ); } catch ( NoSuchObjectException e ) { // Ok } } @Override public void makeRemotelyAvailable( int port, String name ) throws RemoteException { makeRemotelyAvailable( "localhost", port, name ); } @Override public void makeRemotelyAvailable( String host, int port, String name ) throws RemoteException { RmiLocation.location( host, port, name ).bind( this ); } @Override public String[] getAllAvailableCommands() throws RemoteException { return actual.getAllAvailableCommands(); } @Override public TabCompletion tabComplete( Serializable clientId, String partOfLine ) throws ShellException, RemoteException { return actual.tabComplete( clientId, partOfLine ); } @Override public void setSessionVariable( Serializable clientID, String key, Object value ) throws RemoteException, ShellException { actual.setSessionVariable( clientID, key, value ); } }
false
community_shell_src_main_java_org_neo4j_shell_impl_RemotelyAvailableServer.java
1,507
public class RemoteOutput extends UnicastRemoteObject implements Output { private RemoteOutput() throws RemoteException { super(); } /** * Convenient method for creating a new instance without having to catch * the {@link RemoteException} * @return a new {@link RemoteOutput} instance. */ public static RemoteOutput newOutput() { try { return new RemoteOutput(); } catch ( RemoteException e ) { throw new RuntimeException( e ); } } public void print( Serializable object ) { System.out.print( object ); } public void println() { System.out.println(); } public void println( Serializable object ) { System.out.println( object ); } public Appendable append( char ch ) { this.print( ch ); return this; } /** * A util method for getting the correct string for {@code sequence}, * see {@link Appendable}. * @param sequence the string value. * @return the correct string. */ public static String asString( CharSequence sequence ) { return sequence == null ? "null" : sequence.toString(); } public Appendable append( CharSequence sequence ) { this.println( asString( sequence ) ); return this; } public Appendable append( CharSequence sequence, int start, int end ) { this.print( asString( sequence ).substring( start, end ) ); return this; } }
false
community_shell_src_main_java_org_neo4j_shell_impl_RemoteOutput.java
1,508
public class RemoteClient extends AbstractClient { private ShellServer server; private final RmiLocation serverLocation; private final Output out; public RemoteClient( Map<String, Serializable> initialSession, RmiLocation serverLocation ) throws ShellException { this( initialSession, serverLocation, RemoteOutput.newOutput() ); } /** * @param serverLocation the RMI location of the server to connect to. * @throws ShellException if no server was found at the RMI location. */ public RemoteClient( Map<String, Serializable> initialSession, RmiLocation serverLocation, Output out ) throws ShellException { super( initialSession ); this.serverLocation = serverLocation; this.out = out; this.server = findRemoteServer(); } private ShellServer findRemoteServer() throws ShellException { try { ShellServer result = ( ShellServer ) this.serverLocation.getBoundObject(); sayHi( result ); updateTimeForMostRecentConnection(); return result; } catch ( RemoteException e ) { throw ShellException.wrapCause( e ); } } public Output getOutput() { return this.out; } public ShellServer getServer() { // Poke the server by calling a method, f.ex. the welcome() method. // If the connection is lost then try to reconnect, using the last // server lookup address. boolean hadServer = this.server != null; boolean shouldTryToReconnect = this.server == null; try { if ( !shouldTryToReconnect ) server.getName(); } catch ( RemoteException e ) { shouldTryToReconnect = true; } Exception originException = null; if ( shouldTryToReconnect ) { this.server = null; try { this.server = findRemoteServer(); if ( hadServer ) getOutput().println( "[Reconnected to server]" ); } catch ( ShellException ee ) { // Ok originException = ee; } catch ( RemoteException ee ) { // Ok originException = ee; } } if ( this.server == null ) { throw new RuntimeException( "Server closed or cannot be reached anymore: " + originException.getMessage(), originException ); } return this.server; } public void shutdown() { super.shutdown(); tryUnexport( this.out ); } }
false
community_shell_src_main_java_org_neo4j_shell_impl_RemoteClient.java
1,509
public class RelationshipToNodeIterable extends IterableWrapper<Node, Relationship> { private final Node fromNode; public RelationshipToNodeIterable( Iterable<Relationship> iterableToWrap, Node fromNode ) { super( iterableToWrap ); this.fromNode = fromNode; } @Override protected Node underlyingObjectToObject( Relationship rel ) { return rel.getOtherNode( fromNode ); } public static Iterable<Node> wrap( Iterable<Relationship> relationships, Node fromNode ) { return new RelationshipToNodeIterable( relationships, fromNode ); } }
false
community_shell_src_main_java_org_neo4j_shell_impl_RelationshipToNodeIterable.java
1,510
public class JLineConsole implements Console { private final Object consoleReader; static JLineConsole newConsoleOrNullIfNotFound( ShellClient client ) { try { Object consoleReader = Class.forName( "jline.ConsoleReader" ).newInstance(); consoleReader.getClass().getMethod( "setBellEnabled", Boolean.TYPE ).invoke( consoleReader, false ); consoleReader.getClass().getMethod( "setBellEnabled", Boolean.TYPE ).invoke( consoleReader, false ); consoleReader.getClass().getMethod( "setUseHistory", Boolean.TYPE ).invoke( consoleReader, true ); Object completor = Class.forName( JLineConsole.class.getPackage().getName() + "." + "ShellTabCompletor" ).getConstructor( ShellClient.class ).newInstance( client ); Class<?> completorClass = Class.forName( "jline.Completor" ); consoleReader.getClass().getMethod( "addCompletor", completorClass ).invoke( consoleReader, completor ); Class<?> historyClass = Class.forName( "jline.History" ); Object history = historyClass.newInstance(); history.getClass().getMethod( "setHistoryFile", File.class ).invoke( history, Paths.get( System.getProperty( "user.home" ), ".neo4j_shell_history" ).toFile() ); consoleReader.getClass().getMethod( "setHistory", historyClass ).invoke( consoleReader, history ); return new JLineConsole( consoleReader, client ); } catch ( RuntimeException e ) { // Only checked exceptions should cause us to return null, // a runtime exception is not expected - it could be an OOM // for instance, throw instead. throw e; } catch ( Exception e ) { return null; } } private JLineConsole( Object consoleReader, ShellClient client ) { this.consoleReader = consoleReader; } @Override public void format( String format, Object... args ) { System.out.print( format ); } @Override public String readLine( String prompt ) { try { consoleReader.getClass().getMethod( "setDefaultPrompt", String.class ).invoke( consoleReader, prompt ); return ( String ) consoleReader.getClass().getMethod( "readLine" ). invoke( consoleReader ); } catch ( RuntimeException e ) { throw e; } catch ( Exception e ) { throw new RuntimeException( e ); } } }
false
community_shell_src_main_java_org_neo4j_shell_impl_JLineConsole.java
1,511
public class CollectingOutput extends UnicastRemoteObject implements Output, Serializable, Iterable<String> { private static final long serialVersionUID = 1L; private static final String lineSeparator = System.getProperty( "line.separator" ); private transient StringWriter stringWriter = new StringWriter(); private transient PrintWriter allLinesAsOne = new PrintWriter( stringWriter ); private final List<String> lines = new ArrayList<String>(); private String ongoingLine = ""; public CollectingOutput() throws RemoteException { super(); } @Override public Appendable append( CharSequence csq, int start, int end ) throws IOException { this.print( RemoteOutput.asString( csq ).substring( start, end ) ); return this; } @Override public Appendable append( char c ) throws IOException { this.print( c ); return this; } @Override public Appendable append( CharSequence csq ) throws IOException { this.print( RemoteOutput.asString( csq ) ); return this; } @Override public void println( Serializable object ) throws RemoteException { print( object ); println(); } @Override public void println() throws RemoteException { lines.add( ongoingLine ); allLinesAsOne.println( ongoingLine ); ongoingLine = ""; } @Override public void print( Serializable object ) throws RemoteException { String string = object.toString(); int index = 0; while ( true ) { index = string.indexOf( lineSeparator, index ); if ( index < 0 ) { ongoingLine += string; break; } String part = string.substring( 0, index ); ongoingLine += part; println(); string = string.substring( index + lineSeparator.length(), string.length() ); } } @Override public Iterator<String> iterator() { return lines.iterator(); } public String asString() { try { allLinesAsOne.flush(); stringWriter.flush(); return stringWriter.getBuffer().toString(); } finally { clear(); } } private void clear() { lines.clear(); ongoingLine = ""; stringWriter = new StringWriter(); allLinesAsOne = new PrintWriter( stringWriter ); } }
false
community_shell_src_main_java_org_neo4j_shell_impl_CollectingOutput.java
1,512
public class ClassLister { private static final String CLASS_NAME_ENDING = ".class"; /** * @param <T> the class type. * @param superClass the class which the resulting classes must implement * or extend. * @param lookInThesePackages an optional collection of which java packages * to search in. If null is specified then all packages are searched. * @return all classes (in the class path) which extends or implements * a certain class. */ public static <T> Collection<Class<? extends T>> listClassesExtendingOrImplementing( Class<? extends T> superClass, Collection<String> lookInThesePackages ) { String classPath = System.getProperty( "java.class.path" ); StringTokenizer tokenizer = new StringTokenizer( classPath, File.pathSeparator ); Collection<Class<? extends T>> classes = new HashSet<Class<? extends T>>(); while ( tokenizer.hasMoreTokens() ) { collectClasses( classes, superClass, lookInThesePackages, tokenizer.nextToken() ); } return Collections.unmodifiableCollection( classes ); } private static <T> void collectClasses( Collection<Class<? extends T>> classes, Class<? extends T> superClass, Collection<String> lookInThesePackages, String classPathToken ) { File directory = new File( classPathToken ); if ( !directory.exists() ) { return; } try { if ( directory.isDirectory() ) { collectFromDirectory( classes, superClass, lookInThesePackages, "", directory ); } else { JarFile jarFile = new JarFile( directory ); Enumeration<JarEntry> entries = jarFile.entries(); while ( entries.hasMoreElements() ) { JarEntry entry = entries.nextElement(); String entryName = fixJarEntryClassName( entry.getName() ); tryCollectClass( classes, superClass, lookInThesePackages, entryName ); } } } catch ( IOException e ) { throw new RuntimeException( "Error collecting classes from " + classPathToken, e ); } } private static <T> void collectFromDirectory( Collection<Class<? extends T>> classes, Class<? extends T> superClass, Collection<String> lookInThesePackages, String prefix, File directory ) { // Should we even bother walking through these directories? // Check with lookInThesePackages if there's a package matching this. boolean botherToBrowseFurtherDown = false; if ( lookInThesePackages != null ) { for ( String packageName : lookInThesePackages ) { if ( packageName.startsWith( prefix ) ) { botherToBrowseFurtherDown = true; break; } } } else { botherToBrowseFurtherDown = true; } if ( !botherToBrowseFurtherDown ) { return; } File[] files = directory.listFiles(); if ( files == null ) { return; } for ( File file : files ) { if ( file.isDirectory() ) { collectFromDirectory( classes, superClass, lookInThesePackages, addToPrefix( prefix, file.getName() ), file ); } else { String className = addToPrefix( prefix, file.getName() ); className = trimFromClassEnding( className ); tryCollectClass( classes, superClass, lookInThesePackages, className ); } } } private static String addToPrefix( String prefix, String toAdd ) { prefix = prefix == null ? "" : prefix; if ( prefix.length() > 0 ) { prefix += "."; } prefix += toAdd; return prefix; } private static String trimFromClassEnding( String className ) { if ( className.endsWith( CLASS_NAME_ENDING ) ) { className = className.substring( 0, className.length() - CLASS_NAME_ENDING.length() ); } return className; } private static String fixJarEntryClassName( String entryName ) { entryName = entryName.replace( File.separatorChar, '.' ); entryName = entryName.replace( '/', '.' ); return trimFromClassEnding( entryName ); } private static <T> void tryCollectClass( Collection<Class<? extends T>> classes, Class<? extends T> superClass, Collection<String> lookInThesePackages, String className ) { try { if ( !classNameIsInPackage( className, lookInThesePackages ) ) { return; } Class<? extends T> cls = Class.forName( className ).asSubclass( superClass ); if ( cls.isInterface() || Modifier.isAbstract( cls.getModifiers() ) ) { return; } if ( superClass.isAssignableFrom( cls ) ) { classes.add( cls ); } } catch ( Throwable e ) { // Ok } } private static boolean classNameIsInPackage( String className, Collection<String> lookInThesePackages ) { if ( lookInThesePackages == null ) { return true; } String packageName = packageForClassName( className ); return lookInThesePackages.contains( packageName ); } private static String packageForClassName( String className ) { int index = className.lastIndexOf( '.' ); if ( index == -1 ) { return className; } return className.substring( 0, index ); } }
false
community_shell_src_main_java_org_neo4j_shell_impl_ClassLister.java
1,513
{ @Override public String getReplacement( ShellServer server, Session session ) throws ShellException { return "Hello"; } } );
false
community_shell_src_test_java_org_neo4j_shell_impl_BashVariableInterpreterTest.java
1,514
public class BashVariableInterpreterTest { @Test public void shouldInterpretDate() throws Exception { // WHEN String interpreted = interpreter.interpret( "Date:\\d", server, session ); // THEN String datePart = interpreted.substring( "Date:".length() ); assertNotNull( new SimpleDateFormat( "EEE MMM dd" ).parse( datePart ) ); } @Test public void shouldInterpretTime() throws Exception { // WHEN String interpreted = interpreter.interpret( "Time:\\t", server, session ); // THEN String datePart = interpreted.substring( "Time:".length() ); assertNotNull( new SimpleDateFormat( "HH:mm:ss" ).parse( datePart ) ); } @Test public void customInterpreter() throws Exception { // GIVEN interpreter.addReplacer( "test", new Replacer() { @Override public String getReplacement( ShellServer server, Session session ) throws ShellException { return "Hello"; } } ); // WHEN String interpreted = interpreter.interpret( "\\test world", server, session ); // THEN assertEquals( "Hello world", interpreted ); } private final BashVariableInterpreter interpreter = new BashVariableInterpreter(); private final Session session = new Session( 0 ); private ShellServer server; @Before public void before() throws Exception { server = mock( ShellServer.class ); when( server.getName() ).thenReturn( "Server" ); } }
false
community_shell_src_test_java_org_neo4j_shell_impl_BashVariableInterpreterTest.java
1,515
public static class StaticReplacer implements Replacer { private final String value; /** * @param value the value to return from * {@link #getReplacement(ShellServer, Session)}. */ public StaticReplacer( String value ) { this.value = value; } @Override public String getReplacement( ShellServer server, Session session ) { return this.value; } }
false
community_shell_src_main_java_org_neo4j_shell_impl_BashVariableInterpreter.java
1,516
public static class HostReplacer implements Replacer { @Override public String getReplacement( ShellServer server, Session session ) { try { return server.getName(); } catch ( RemoteException e ) { return ""; } } }
false
community_shell_src_main_java_org_neo4j_shell_impl_BashVariableInterpreter.java
1,517
public static class DateReplacer implements Replacer { private final DateFormat format; /** * @param format the date format, see {@link SimpleDateFormat}. */ public DateReplacer( String format ) { this.format = new SimpleDateFormat( format ); } @Override public String getReplacement( ShellServer server, Session session ) { return format.format( new Date() ); } }
false
community_shell_src_main_java_org_neo4j_shell_impl_BashVariableInterpreter.java
1,518
public class BashVariableInterpreter { private static final Map<String, Replacer> STATIC_REPLACERS = new HashMap<String, Replacer>(); static { STATIC_REPLACERS.put( "d", new DateReplacer( "EEE MMM dd" ) ); STATIC_REPLACERS.put( "h", new HostReplacer() ); STATIC_REPLACERS.put( "H", new HostReplacer() ); STATIC_REPLACERS.put( "s", new HostReplacer() ); STATIC_REPLACERS.put( "t", new DateReplacer( "HH:mm:ss" ) ); STATIC_REPLACERS.put( "T", new DateReplacer( "KK:mm:ss" ) ); STATIC_REPLACERS.put( "@", new DateReplacer( "KK:mm aa" ) ); STATIC_REPLACERS.put( "A", new DateReplacer( "HH:mm" ) ); STATIC_REPLACERS.put( "u", new StaticReplacer( "user" ) ); STATIC_REPLACERS.put( "v", new StaticReplacer( getKernel().getReleaseVersion() ) ); STATIC_REPLACERS.put( "V", new StaticReplacer( getKernel().getVersion() ) ); } private final Map<String, Replacer> localReplacers = new HashMap<String, Replacer>(); /** * Adds a customized replacer for a certain variable. * @param key the variable key, f.ex. "t". * @param replacer the replacer which gives a replacement for the variable. */ public void addReplacer( String key, Replacer replacer ) { localReplacers.put( key, replacer ); } /** * Interprets a string with variables in it and replaces those variables * with values from replacers, see {@link Replacer}. * @param string the string to interpret. * @param server the server which runs the interpretation. * @param session the session (or environment) of the interpretation. * @return the interpreted string. * @throws ShellException if there should be some communication error. */ public String interpret( String string, ShellServer server, Session session ) throws ShellException { string = replace( string, server, session, localReplacers ); string = replace( string, server, session, STATIC_REPLACERS ); return string; } private String replace( String string, ShellServer server, Session session, Map<String, Replacer> replacers ) throws ShellException { for ( Map.Entry<String, Replacer> replacer : replacers.entrySet() ) { String value = replacer.getValue().getReplacement( server, session ); string = string.replaceAll( "\\\\" + replacer.getKey(), value ); } return string; } /** * A replacer which can return a string to replace a variable. */ public static interface Replacer { /** * Returns a string to replace something else. * @param server the server which runs the interpretation. * @param session the environment of the interpretation. * @return the replacement. * @throws ShellException if there should be some communication error. */ String getReplacement( ShellServer server, Session session ) throws ShellException; } /** * A {@link Replacer} which gets instantiated with a string representing the * replacement, which means that the value returned from * {@link #getReplacement(ShellServer, Session)} is always the same. */ public static class StaticReplacer implements Replacer { private final String value; /** * @param value the value to return from * {@link #getReplacement(ShellServer, Session)}. */ public StaticReplacer( String value ) { this.value = value; } @Override public String getReplacement( ShellServer server, Session session ) { return this.value; } } /** * A {@link Replacer} which returns a date string in a certain format. */ public static class DateReplacer implements Replacer { private final DateFormat format; /** * @param format the date format, see {@link SimpleDateFormat}. */ public DateReplacer( String format ) { this.format = new SimpleDateFormat( format ); } @Override public String getReplacement( ShellServer server, Session session ) { return format.format( new Date() ); } } /** * Returns the name of the server (or "host"). */ public static class HostReplacer implements Replacer { @Override public String getReplacement( ShellServer server, Session session ) { try { return server.getName(); } catch ( RemoteException e ) { return ""; } } } }
false
community_shell_src_main_java_org_neo4j_shell_impl_BashVariableInterpreter.java
1,519
public abstract class AbstractClient implements ShellClient { public static final String WARN_UNTERMINATED_INPUT = "Warning: Exiting with unterminated multi-line input."; private static final Set<String> EXIT_COMMANDS = new HashSet<>( Arrays.asList( "exit", "quit", null ) ); private Console console; private long timeConnection; private volatile boolean end; private final Collection<String> multiLine = new ArrayList<>(); private Serializable id; private String prompt; private final Map<String, Serializable> initialSession; public AbstractClient( Map<String, Serializable> initialSession ) { this.initialSession = initialSession; } public void grabPrompt() { init(); while ( !end ) { try { evaluate( readLine( getPrompt() ) ); } catch ( Exception e ) { if ( this.shouldPrintStackTraces() ) { e.printStackTrace(); } else { this.console.format( getShortExceptionMessage( e ) + "\n" ); } } } this.shutdown(); } @Override public void evaluate( String line ) throws ShellException { evaluate( line, getOutput() ); } @Override public void evaluate( String line, Output out ) throws ShellException { if ( EXIT_COMMANDS.contains( line ) ) { end(); return; } boolean success = false; try { String expandedLine = fullLine( line ); //expandLine( fullLine( line ) ); Response response = getServer().interpretLine( id, expandedLine, out ); switch ( response.getContinuation() ) { case INPUT_COMPLETE: endMultiLine(); break; case INPUT_INCOMPLETE: multiLine.add( line ); break; case EXIT: getServer().leave( id ); end(); break; } prompt = response.getPrompt(); success = true; } catch ( RemoteException e ) { throw ShellException.wrapCause( e ); } finally { if ( !success ) endMultiLine(); } } private void endMultiLine() { multiLine.clear(); } private String fullLine( String line ) { if ( multiLine.isEmpty() ) { return line; } StringBuilder result = new StringBuilder(); for ( String oneLine : multiLine ) { result.append( result.length() > 0 ? "\n" : "" ).append( oneLine ); } return result.append( "\n" + line ).toString(); } @Override public void end() { end = true; } protected static String getShortExceptionMessage( Exception e ) { return e.getMessage(); } public String getPrompt() { if ( !multiLine.isEmpty() ) { return "> "; } return prompt; } public boolean shouldPrintStackTraces() { try { String stringValue = (String) getServer().interpretVariable( id, Variables.STACKTRACES_KEY ); return Boolean.parseBoolean( stringValue ); } catch ( Exception e ) { return true; } } protected void init() { try { // To make sure we have a connection to our server. getServer(); // Grab a jline console if available, else a standard one. console = JLineConsole.newConsoleOrNullIfNotFound( this ); if ( console == null ) { System.out.println( "Want bash-like features? throw in " + "jLine (http://jline.sourceforge.net) on the classpath" ); console = new StandardConsole(); } getOutput().println(); } catch ( RemoteException e ) { throw new RuntimeException( e ); } } protected void sayHi( ShellServer server ) throws RemoteException, ShellException { Welcome welcome = server.welcome( initialSession ); id = welcome.getId(); prompt = welcome.getPrompt(); if ( !welcome.getMessage().isEmpty() ) { getOutput().println( welcome.getMessage() ); } } protected String readLine( String prompt ) { return console.readLine( prompt ); } protected void updateTimeForMostRecentConnection() { this.timeConnection = System.currentTimeMillis(); } public long timeForMostRecentConnection() { return timeConnection; } public void shutdown() { if ( !multiLine.isEmpty() ) { try { getOutput().println( WARN_UNTERMINATED_INPUT ); } catch ( RemoteException e ) { throw new RuntimeException( e ); } } } @Override public Serializable getId() { return id; } protected void tryUnexport( Remote remote ) { try { UnicastRemoteObject.unexportObject( remote, true ); } catch ( NoSuchObjectException e ) { System.out.println( "Couldn't unexport: " + remote ); } } @Override public void setSessionVariable( String key, Serializable value ) throws ShellException { try { getServer().setSessionVariable( id, key, value ); } catch ( RemoteException e ) { throw ShellException.wrapCause( e ); } } }
false
community_shell_src_main_java_org_neo4j_shell_impl_AbstractClient.java
1,520
public abstract class AbstractAppServer extends SimpleAppServer implements AppShellServer { private final Map<String, App> apps = new TreeMap<>(); /** * Constructs a new server. * @throws RemoteException if there's an RMI error. */ public AbstractAppServer() throws RemoteException { super(); for ( App app : Service.load( App.class ) ) { addApp( app ); } } private void addApp( App app ) { apps.put( app.getName(), app ); try { ( (AbstractApp) app ).setServer( this ); } catch ( Exception e ) { // TODO It's OK, or is it? } } @Override public App findApp( String command ) { return apps.get( command ); } @Override public void shutdown() throws RemoteException { for ( App app : this.apps.values() ) { app.shutdown(); } super.shutdown(); } @Override public Response interpretLine( Serializable clientId, String line, Output out ) throws ShellException { Session session = getClientSession( clientId ); if ( line == null || line.trim().length() == 0 ) { return new Response( getPrompt( session ), Continuation.INPUT_COMPLETE ); } try { Continuation commandResult = null; for ( String command : line.split( Pattern.quote( "&&" ) ) ) { command = TextUtil.removeSpaces( command ); command = replaceAlias( command, session ); AppCommandParser parser = new AppCommandParser( this, command ); commandResult = parser.app().execute( parser, session, out ); } return new Response( getPrompt( session ), commandResult ); } catch ( Exception e ) { throw wrapException( e ); } } protected String replaceAlias( String line, Session session ) { boolean changed = true; Set<String> appNames = new HashSet<>(); while ( changed ) { changed = false; String appName = AppCommandParser.parseOutAppName( line ); String alias = session.getAlias( appName ); if ( alias != null && appNames.add( alias ) ) { changed = true; line = alias + line.substring( appName.length() ); } } return line; } @Override public String[] getAllAvailableCommands() { return apps.keySet().toArray( new String[apps.size()] ); } @Override public TabCompletion tabComplete( Serializable clientID, String partOfLine ) throws ShellException, RemoteException { // TODO We can't assume it's an AppShellServer, can we? try { AppCommandParser parser = new AppCommandParser( this, partOfLine ); App app = parser.app(); List<String> appCandidates = app.completionCandidates( partOfLine, getClientSession( clientID ) ); appCandidates = quote( appCandidates ); if ( appCandidates.size() == 1 ) { appCandidates.set( 0, appCandidates.get( 0 ) + " " ); } int cursor = partOfLine.length() - TextUtil.lastWordOrQuoteOf( partOfLine, true ).length(); return new TabCompletion( appCandidates, cursor ); } catch ( Exception e ) { throw wrapException( e ); } } protected ShellException wrapException( Exception e ) { return ShellException.wrapCause( e ); } private static List<String> quote( List<String> candidates ) { List<String> result = new ArrayList<>(); for ( String candidate : candidates ) { candidate = candidate.replaceAll( " ", "\\\\ " ); result.add( candidate ); } return result; } }
false
community_shell_src_main_java_org_neo4j_shell_impl_AbstractAppServer.java
1,521
public abstract class AbstractApp implements App { private final Map<String, OptionDefinition> optionDefinitions = new HashMap<>(); private AppShellServer server; @Override public String getName() { return this.getClass().getSimpleName().toLowerCase(); } @Override public OptionDefinition getOptionDefinition( String option ) { return this.optionDefinitions.get( option ); } protected void addOptionDefinition( String option, OptionDefinition definition ) { this.optionDefinitions.put( option, definition ); } @Override public String[] getAvailableOptions() { String[] result = this.optionDefinitions.keySet().toArray( new String[ this.optionDefinitions.size() ] ); Arrays.sort( result ); return result; } public void setServer( AppShellServer server ) { if ( this.server != null ) throw new IllegalStateException( "Server already set" ); this.server = server; } @Override public AppShellServer getServer() { return this.server; } @Override public String getDescription() { return null; } @Override public String getDescription( String option ) { OptionDefinition definition = this.optionDefinitions.get( option ); return definition == null ? null : definition.getDescription(); } @Override public void shutdown() { // Default behavior is to do nothing } @Override public List<String> completionCandidates( String partOfLine, Session session ) throws ShellException { return Collections.emptyList(); } protected static Map<String, Object> parseFilter( String filterString, Output out ) throws RemoteException, ShellException { if ( filterString == null ) { return new HashMap<>(); } Map<String, Object> map; String signsOfJSON = ":"; int numberOfSigns = 0; for ( int i = 0; i < signsOfJSON.length(); i++ ) { if ( filterString.contains( String.valueOf( signsOfJSON.charAt( i ) ) ) ) { numberOfSigns++; } } if ( numberOfSigns >= 1 ) { String jsonString = filterString; if ( !jsonString.startsWith( "{" ) ) { jsonString = "{" + jsonString; } if ( !jsonString.endsWith( "}" ) ) { jsonString += "}"; } try { map = parseJSONMap( jsonString ); } catch ( JSONException e ) { out.println( "parser: \"" + filterString + "\" hasn't got " + "correct JSON formatting: " + e.getMessage() ); throw ShellException.wrapCause( e ); } } else { map = new HashMap<>(); map.put( filterString, null ); } return map; } protected static Map<String, Object> parseJSONMap( String jsonString ) throws JSONException { JSONObject object = new JSONObject( jsonString ); Map<String, Object> result = new HashMap<>(); for ( String name : JSONObject.getNames( object ) ) { Object value = object.get( name ); if ( value != null && value instanceof String && ( ( String ) value ).length() == 0 ) { value = null; } result.put( name, value ); } return result; } protected static Object[] parseArray( String string ) { try { JSONArray array = new JSONArray( string ); Object[] result = new Object[ array.length() ]; for ( int i = 0; i < result.length; i++ ) { result[ i ] = array.get( i ); } return result; } catch ( JSONException e ) { throw new IllegalArgumentException( e.getMessage(), e ); } } @Override public boolean takesOptions() { return !optionDefinitions.isEmpty(); } }
false
community_shell_src_main_java_org_neo4j_shell_impl_AbstractApp.java
1,522
static class ArgReader implements Iterator<String> { private static final int START_INDEX = -1; private int index = START_INDEX; private final String[] args; private Integer mark; ArgReader( String[] args ) { this.args = args; } @Override public boolean hasNext() { return this.index + 1 < this.args.length; } @Override public String next() { if ( !hasNext() ) { throw new NoSuchElementException(); } this.index++; return this.args[ this.index ]; } /** * Goes to the previous argument. */ public void previous() { this.index--; if ( this.index < START_INDEX ) { this.index = START_INDEX; } } @Override public void remove() { throw new UnsupportedOperationException(); } /** * Marks the position so that a call to {@link #flip()} returns to that * position. */ public void mark() { this.mark = this.index; } /** * Flips back to the position defined in {@link #mark()}. */ public void flip() { if ( this.mark == null ) { throw new IllegalStateException(); } this.index = this.mark; this.mark = null; } }
false
community_shell_src_main_java_org_neo4j_shell_apps_extra_ScriptExecutor.java
1,523
public class ShellBootstrap implements Serializable { private final boolean enable; private String host; private final int port; private final String name; private final boolean read_only; ShellBootstrap( Config config ) { this.enable = config.get( ShellSettings.remote_shell_enabled ); this.host = config.get( ShellSettings.remote_shell_host ); this.port = config.get( ShellSettings.remote_shell_port ); this.name = config.get( ShellSettings.remote_shell_name ); this.read_only = config.get( ShellSettings.remote_shell_read_only ); } public ShellBootstrap( int port, String name ) { enable = true; this.port = port; this.name = name; this.read_only = false; } public String serialize() { ByteArrayOutputStream os = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new ObjectOutputStream( os ); oos.writeObject( this ); oos.close(); } catch ( IOException e ) { throw new RuntimeException( "Broken implementation!", e ); } return new sun.misc.BASE64Encoder().encode( os.toByteArray() ); } static String serializeStub( Remote obj ) { ByteArrayOutputStream os = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new ObjectOutputStream( os ); oos.writeObject( RemoteObject.toStub( obj ) ); oos.close(); } catch ( IOException e ) { throw new RuntimeException( "Broken implementation!", e ); } return new sun.misc.BASE64Encoder().encode( os.toByteArray() ); } static ShellBootstrap deserialize( String data ) { try { return (ShellBootstrap) new ObjectInputStream( new ByteArrayInputStream( new sun.misc.BASE64Decoder().decodeBuffer( data ) ) ).readObject(); } catch ( Exception e ) { return null; } } @SuppressWarnings("boxing") GraphDatabaseShellServer load( GraphDatabaseAPI graphDb ) throws RemoteException { if ( !enable ) { return null; } return enable( new GraphDatabaseShellServer( graphDb, read_only ) ); } void visit( GraphDatabaseShellServer state ) { // TODO: use for Registry-less connection } public GraphDatabaseShellServer enable( GraphDatabaseShellServer server ) throws RemoteException { server.makeRemotelyAvailable( host, port, name ); return server; } }
false
community_shell_src_main_java_org_neo4j_shell_impl_ShellBootstrap.java
1,524
@Service.Implementation(KernelExtensionFactory.class) public final class ShellServerExtensionFactory extends KernelExtensionFactory<ShellServerExtensionFactory.Dependencies> { static final String KEY = "shell"; public interface Dependencies { Config getConfig(); GraphDatabaseAPI getGraphDatabaseAPI(); } public ShellServerExtensionFactory() { super( KEY ); } @Override public Class getSettingsClass() { return ShellSettings.class; } @Override public Lifecycle newKernelExtension( Dependencies dependencies ) throws Throwable { return new ShellServerKernelExtension( dependencies.getConfig(), dependencies.getGraphDatabaseAPI() ); } }
false
community_shell_src_main_java_org_neo4j_shell_impl_ShellServerExtensionFactory.java
1,525
public class PathShellApp extends NonTransactionProvidingApp { { addOptionDefinition( "a", new OptionDefinition( OptionValueType.MUST, "Which algorithm to use" ) ); addOptionDefinition( "m", new OptionDefinition( OptionValueType.MUST, "Maximum depth to traverse" ) ); addOptionDefinition( "f", new OptionDefinition( OptionValueType.MUST, "Relationship types and directions, f.ex: {KNOWS:out,LOVES:both}" ) ); addOptionDefinition( "from", new OptionDefinition( OptionValueType.MUST, "Use some other star point than the current node" ) ); addOptionDefinition( "q", new OptionDefinition( OptionValueType.NONE, "More quiet, print less verbose paths" ) ); addOptionDefinition( "s", new OptionDefinition( OptionValueType.NONE, "Find max one path" ) ); } @Override public String getDescription() { return "Displays paths from current (or any node) to another node using supplied algorithm. Usage:\n" + "\n# Find shortest paths from current to node 241 at max depth 10" + "\npaths -m 10 -a shortestPath -f KNOWS:out,LOVES:in 241"; } @Override public String getName() { return "paths"; } @Override protected Continuation exec( AppCommandParser parser, Session session, Output out ) throws Exception { String fromString = parser.options().get( "from" ); String toString = parser.argument( 0, "Must supply a 'to' node as first argument" ); String algo = parser.options().get( "a" ); String maxDepthString = parser.options().get( "m" ); boolean quietPrint = parser.options().containsKey( "q" ); boolean caseInsensitiveFilters = parser.options().containsKey( "i" ); boolean looseFilters = parser.options().containsKey( "l" ); int maxDepth = maxDepthString != null ? Integer.parseInt( maxDepthString ) : Integer.MAX_VALUE; fromString = fromString != null ? fromString : String.valueOf( this.getCurrent( session ).getId() ); Map<String, Object> filter = parseFilter( parser.options().get( "f" ), out ); PathExpander expander = toExpander( getServer().getDb(), Direction.BOTH, filter, caseInsensitiveFilters, looseFilters ); PathFinder<Path> finder = expander != null ? getPathFinder( algo, expander, maxDepth, out ) : null; if ( finder != null ) { Node fromNode = getNodeById( Long.parseLong( fromString ) ); Node toNode = getNodeById( Long.parseLong( toString ) ); boolean single = parser.options().containsKey( "s" ); Iterable<Path> paths = single ? Arrays.asList( finder.findSinglePath( fromNode, toNode ) ) : finder.findAllPaths( fromNode, toNode ); for ( Path path : paths ) { printPath( path, quietPrint, session, out ); } } return Continuation.INPUT_COMPLETE; } private PathFinder<Path> getPathFinder( String algo, PathExpander expander, int maxDepth, Output out ) throws Exception { Method method; try { method = GraphAlgoFactory.class.getDeclaredMethod( algo, PathExpander.class, Integer.TYPE ); } catch ( Exception e ) { out.println( "Couldn't find algorithm '" + algo + "'" ); return null; } return (PathFinder) method.invoke( null, expander, maxDepth ); } }
false
community_shell_src_main_java_org_neo4j_shell_apps_extra_PathShellApp.java
1,526
public final class ShellServerKernelExtension implements Lifecycle { private Config config; private GraphDatabaseAPI graphDatabaseAPI; private GraphDatabaseShellServer server; public ShellServerKernelExtension( Config config, GraphDatabaseAPI graphDatabaseAPI ) { this.config = config; this.graphDatabaseAPI = graphDatabaseAPI; } @Override public void init() throws Throwable { } @Override public void start() throws Throwable { server = new ShellBootstrap( config ).load( graphDatabaseAPI ); } @Override public void stop() throws Throwable { if ( server != null ) { server.shutdown(); } } @Override public void shutdown() throws Throwable { } public GraphDatabaseShellServer getServer() { return server; } }
false
community_shell_src_main_java_org_neo4j_shell_impl_ShellServerKernelExtension.java
1,527
@Service.Implementation( App.class ) public class Cd extends TransactionProvidingApp { private static final String START_ALIAS = "start"; private static final String END_ALIAS = "end"; /** * Constructs a new cd application. */ public Cd() { this.addOptionDefinition( "a", new OptionDefinition( OptionValueType.NONE, "Absolute id, new primitive doesn't need to be connected to the current one" ) ); this.addOptionDefinition( "r", new OptionDefinition( OptionValueType.NONE, "Makes the supplied id represent a relationship instead of a node" ) ); } @Override public String getDescription() { return "Changes the current node or relationship, i.e. traverses " + "one step to another node or relationship. Usage: cd <id>"; } @Override protected List<String> completionCandidatesInTx( String partOfLine, Session session ) throws ShellException { String lastWord = lastWordOrQuoteOf( partOfLine, false ); if ( lastWord.startsWith( "-" ) ) { return super.completionCandidates( partOfLine, session ); } NodeOrRelationship current; try { current = getCurrent( session ); } catch ( ShellException e ) { return Collections.emptyList(); } TreeSet<String> result = new TreeSet<>(); if ( current.isNode() ) { // TODO Check if -r is supplied Node node = current.asNode(); for ( Node otherNode : RelationshipToNodeIterable.wrap( node.getRelationships(), node ) ) { long otherNodeId = otherNode.getId(); String title = findTitle( session, otherNode ); if ( title != null ) { if ( !result.contains( title ) ) { maybeAddCompletionCandidate( result, title + "," + otherNodeId, lastWord ); } } maybeAddCompletionCandidate( result, "" + otherNodeId, lastWord ); } } else { maybeAddCompletionCandidate( result, START_ALIAS, lastWord ); maybeAddCompletionCandidate( result, END_ALIAS, lastWord ); Relationship rel = current.asRelationship(); maybeAddCompletionCandidate( result, "" + rel.getStartNode().getId(), lastWord ); maybeAddCompletionCandidate( result, "" + rel.getEndNode().getId(), lastWord ); } return new ArrayList<>( result ); } private static void maybeAddCompletionCandidate( Collection<String> candidates, String candidate, String lastWord ) { if ( lastWord.length() == 0 || candidate.startsWith( lastWord ) ) { candidates.add( candidate ); } } @Override protected Continuation exec( AppCommandParser parser, Session session, Output out ) throws ShellException, RemoteException { List<TypedId> paths = readCurrentWorkingDir( session ); NodeOrRelationship newThing = null; if ( parser.arguments().isEmpty() ) { clearCurrent( session ); writeCurrentWorkingDir( paths, session ); return Continuation.INPUT_COMPLETE; } else { NodeOrRelationship current = null; try { current = getCurrent( session ); } catch ( ShellException e ) { // Ok, didn't exist } String arg = parser.arguments().get( 0 ); TypedId newId = null; if ( arg.equals( ".." ) ) { if ( paths.size() > 0 ) { newId = paths.remove( paths.size() - 1 ); } } else if ( arg.equals( "." ) ) { // Do nothing } else if ( arg.equals( START_ALIAS ) || arg.equals( END_ALIAS ) ) { if ( current == null ) { throw new ShellException( "Can't do " + START_ALIAS + " or " + END_ALIAS + " on a non-existent relationship" ); } newId = getStartOrEnd( current, arg ); paths.add( current.getTypedId() ); } else { long suppliedId = -1; try { suppliedId = Long.parseLong( arg ); } catch ( NumberFormatException e ) { if ( current != null ) { suppliedId = findNodeWithTitle( current.asNode(), arg, session ); } if ( suppliedId == -1 ) { throw new ShellException( "No connected node with title '" + arg + "'" ); } } newId = parser.options().containsKey( "r" ) ? new TypedId( NodeOrRelationship.TYPE_RELATIONSHIP, suppliedId ) : new TypedId( NodeOrRelationship.TYPE_NODE, suppliedId ); if ( current != null && newId.equals( current.getTypedId() ) ) { throw new ShellException( "Can't cd to where you stand" ); } boolean absolute = parser.options().containsKey( "a" ); if ( !absolute && current != null && !isConnected( current, newId ) ) { throw new ShellException( getDisplayName( getServer(), session, newId, false ) + " isn't connected to the current primitive," + " use -a to force it to go there anyway" ); } if ( current != null ) { paths.add( current.getTypedId() ); } } newThing = newId != null ? getThingById( newId ) : current; } if ( newThing != null ) { setCurrent( session, newThing ); } else { clearCurrent( session ); } writeCurrentWorkingDir( paths, session ); return Continuation.INPUT_COMPLETE; } private long findNodeWithTitle( Node node, String match, Session session ) throws ShellException { Object[] matchParts = splitNodeTitleAndId( match ); if ( matchParts[1] != null ) { return (Long) matchParts[1]; } String titleMatch = (String) matchParts[0]; for ( Node otherNode : RelationshipToNodeIterable.wrap( node.getRelationships(), node ) ) { String title = findTitle( session, otherNode ); if ( titleMatch.equals( title ) ) { return otherNode.getId(); } } return -1; } private Object[] splitNodeTitleAndId( String string ) { int index = string.lastIndexOf( "," ); String title = null; Long id = null; try { id = Long.parseLong( string.substring( index + 1 ) ); title = string.substring( 0, index ); } catch ( NumberFormatException e ) { title = string; } return new Object[] { title, id }; } private TypedId getStartOrEnd( NodeOrRelationship current, String arg ) throws ShellException { if ( !current.isRelationship() ) { throw new ShellException( "Only allowed on relationships" ); } Node newNode = null; if ( arg.equals( START_ALIAS ) ) { newNode = current.asRelationship().getStartNode(); } else if ( arg.equals( END_ALIAS ) ) { newNode = current.asRelationship().getEndNode(); } else { throw new ShellException( "Unknown alias '" + arg + "'" ); } return NodeOrRelationship.wrap( newNode ).getTypedId(); } private boolean isConnected( NodeOrRelationship current, TypedId newId ) { if ( current.isNode() ) { Node currentNode = current.asNode(); long startTime = System.currentTimeMillis(); for ( Relationship rel : currentNode.getRelationships() ) { if ( newId.isNode() ) { if ( rel.getOtherNode( currentNode ).getId() == newId.getId() ) { return true; } } else { if ( rel.getId() == newId.getId() ) { return true; } } if ( System.currentTimeMillis()-startTime > 350 ) { // DOn't spend too long time in here return true; } } } else { if ( newId.isRelationship() ) { return false; } Relationship relationship = current.asRelationship(); if ( relationship.getStartNode().getId() == newId.getId() || relationship.getEndNode().getId() == newId.getId() ) { return true; } } return false; } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_Cd.java
1,528
@Service.Implementation(App.class) public class Begin extends NonTransactionProvidingApp { @Override public String getDescription() { return "Opens a transaction"; } @Override protected Continuation exec( AppCommandParser parser, Session session, Output out ) throws ShellException, RemoteException { String lineWithoutApp = parser.getLineWithoutApp(); if ( !acceptableText( lineWithoutApp ) ) { out.println( "Error: To open a transaction, write BEGIN TRANSACTION" ); return Continuation.INPUT_COMPLETE; } Transaction tx = currentTransaction( getServer() ); // This is a "begin" app so it will leave a transaction open. Don't close it in here getServer().getDb().beginTx(); Integer txCount = session.getCommitCount(); int count; if ( txCount == null ) { if ( tx == null ) { count = 0; out.println( "Transaction started" ); } else { count = 1; out.println( "Warning: transaction found that was not started by the shell." ); } } else { count = txCount; out.println( String.format( "Nested transaction started (Tx count: %d)", count + 1 ) ); } session.setCommitCount( ++count ); return Continuation.INPUT_COMPLETE; } private static String TRANSACTION = "TRANSACTION"; private boolean acceptableText( String line ) { if ( line == null || line.length() > TRANSACTION.length() ) { return false; } String substring = TRANSACTION.substring( 0, line.length() ); return substring.equals( line.toUpperCase() ); } public static Transaction currentTransaction( GraphDatabaseShellServer server ) throws ShellException { try { return server.getDb().getDependencyResolver().resolveDependency( TransactionManager.class ).getTransaction(); } catch ( SystemException e ) { throw new ShellException( e.getMessage() ); } } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_Begin.java
1,529
private class ReadOnlySchemaProxy implements Schema { private final Schema actual; public ReadOnlySchemaProxy( Schema actual ) { this.actual = actual; } @Override public IndexCreator indexFor( Label label ) { throw readOnlyException(); } @Override public Iterable<IndexDefinition> getIndexes( Label label ) { return actual.getIndexes( label ); } @Override public Iterable<IndexDefinition> getIndexes() { return actual.getIndexes(); } @Override public IndexState getIndexState( IndexDefinition index ) { return actual.getIndexState( index ); } @Override public String getIndexFailure( IndexDefinition index ) { return actual.getIndexFailure( index ); } @Override public void awaitIndexOnline( IndexDefinition index, long duration, TimeUnit unit ) { actual.awaitIndexOnline( index, duration, unit ); } @Override public void awaitIndexesOnline( long duration, TimeUnit unit ) { actual.awaitIndexesOnline( duration, unit ); } @Override public ConstraintCreator constraintFor( Label label ) { throw readOnlyException(); } @Override public Iterable<ConstraintDefinition> getConstraints() { return actual.getConstraints(); } @Override public Iterable<ConstraintDefinition> getConstraints( Label label ) { return actual.getConstraints( label ); } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_ReadOnlyGraphDatabaseProxy.java
1,530
private class ReadOnlyRelationshipProxy implements Relationship { private final Relationship actual; ReadOnlyRelationshipProxy( Relationship actual ) { this.actual = actual; } @Override public int hashCode() { return actual.hashCode(); } @Override public boolean equals( Object obj ) { return (obj instanceof Relationship) && ((Relationship) obj).getId() == getId(); } @Override public String toString() { return actual.toString(); } @Override public long getId() { return actual.getId(); } @Override public void delete() { readOnly(); } @Override public Node getEndNode() { return new ReadOnlyNodeProxy( actual.getEndNode() ); } @Override public Node[] getNodes() { return new Node[]{getStartNode(), getEndNode()}; } @Override public Node getOtherNode( Node node ) { return new ReadOnlyNodeProxy( actual.getOtherNode( node ) ); } @Override public Node getStartNode() { return new ReadOnlyNodeProxy( actual.getStartNode() ); } @Override public RelationshipType getType() { return actual.getType(); } @Override public boolean isType( RelationshipType type ) { return actual.isType( type ); } @Override public GraphDatabaseService getGraphDatabase() { return ReadOnlyGraphDatabaseProxy.this; } @Override public Object getProperty( String key ) { return actual.getProperty( key ); } @Override public Object getProperty( String key, Object defaultValue ) { return actual.getProperty( key, defaultValue ); } @Override public Iterable<String> getPropertyKeys() { return actual.getPropertyKeys(); } @Override public boolean hasProperty( String key ) { return actual.hasProperty( key ); } @Override public Object removeProperty( String key ) { return readOnly(); } @Override public void setProperty( String key, Object value ) { readOnly(); } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_ReadOnlyGraphDatabaseProxy.java
1,531
class ReadOnlyRelationshipIndexProxy extends ReadOnlyIndexProxy<Relationship, RelationshipIndex> implements RelationshipIndex { ReadOnlyRelationshipIndexProxy( RelationshipIndex actual ) { super( actual ); } @Override Relationship wrap( Relationship actual ) { return readOnly( actual ); } @Override public IndexHits<Relationship> get( String key, Object valueOrNull, Node startNodeOrNull, Node endNodeOrNull ) { return new ReadOnlyIndexHitsProxy<Relationship>( this, actual.get( key, valueOrNull, startNodeOrNull, endNodeOrNull ) ); } @Override public IndexHits<Relationship> query( String key, Object queryOrQueryObjectOrNull, Node startNodeOrNull, Node endNodeOrNull ) { return new ReadOnlyIndexHitsProxy<Relationship>( this, actual.query( key, queryOrQueryObjectOrNull, startNodeOrNull, endNodeOrNull ) ); } @Override public IndexHits<Relationship> query( Object queryOrQueryObjectOrNull, Node startNodeOrNull, Node endNodeOrNull ) { return new ReadOnlyIndexHitsProxy<Relationship>( this, actual.query( queryOrQueryObjectOrNull, startNodeOrNull, endNodeOrNull ) ); } @Override public String getName() { return actual.getName(); } @Override public Class<Relationship> getEntityType() { return Relationship.class; } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_ReadOnlyGraphDatabaseProxy.java
1,532
private class ReadOnlyNodeProxy implements Node { private final Node actual; ReadOnlyNodeProxy( Node actual ) { this.actual = actual; } @Override public int hashCode() { return actual.hashCode(); } @Override public boolean equals( Object obj ) { return (obj instanceof Node) && ((Node) obj).getId() == getId(); } @Override public String toString() { return actual.toString(); } @Override public long getId() { return actual.getId(); } @Override public Relationship createRelationshipTo( Node otherNode, RelationshipType type ) { return readOnly(); } @Override public void delete() { readOnly(); } @Override public Iterable<Relationship> getRelationships() { return relationships( actual.getRelationships() ); } @Override public Iterable<Relationship> getRelationships( RelationshipType... types ) { return relationships( actual.getRelationships( types ) ); } @Override public Iterable<Relationship> getRelationships( Direction direction, RelationshipType... types ) { return relationships( actual.getRelationships( direction, types ) ); } @Override public Iterable<Relationship> getRelationships( Direction dir ) { return relationships( actual.getRelationships( dir ) ); } @Override public Iterable<Relationship> getRelationships( RelationshipType type, Direction dir ) { return relationships( actual.getRelationships( type, dir ) ); } @Override public Relationship getSingleRelationship( RelationshipType type, Direction dir ) { return new ReadOnlyRelationshipProxy( actual.getSingleRelationship( type, dir ) ); } @Override public boolean hasRelationship() { return actual.hasRelationship(); } @Override public boolean hasRelationship( RelationshipType... types ) { return actual.hasRelationship( types ); } @Override public boolean hasRelationship( Direction direction, RelationshipType... types ) { return actual.hasRelationship( direction, types ); } @Override public boolean hasRelationship( Direction dir ) { return actual.hasRelationship( dir ); } @Override public boolean hasRelationship( RelationshipType type, Direction dir ) { return actual.hasRelationship( type, dir ); } @Override public Traverser traverse( Order traversalOrder, StopEvaluator stopEvaluator, ReturnableEvaluator returnableEvaluator, RelationshipType relationshipType, Direction direction ) { return OldTraverserWrapper.traverse( this, traversalOrder, stopEvaluator, returnableEvaluator, relationshipType, direction ); } @Override public Traverser traverse( Order traversalOrder, StopEvaluator stopEvaluator, ReturnableEvaluator returnableEvaluator, RelationshipType firstRelationshipType, Direction firstDirection, RelationshipType secondRelationshipType, Direction secondDirection ) { return OldTraverserWrapper.traverse( this, traversalOrder, stopEvaluator, returnableEvaluator, firstRelationshipType, firstDirection, secondRelationshipType, secondDirection ); } @Override public Traverser traverse( Order traversalOrder, StopEvaluator stopEvaluator, ReturnableEvaluator returnableEvaluator, Object... relationshipTypesAndDirections ) { return OldTraverserWrapper.traverse( this, traversalOrder, stopEvaluator, returnableEvaluator, relationshipTypesAndDirections ); } @Override public void addLabel( Label label ) { readOnly(); } @Override public void removeLabel( Label label ) { readOnly(); } @Override public boolean hasLabel( Label label ) { return actual.hasLabel( label ); } @Override public Iterable<Label> getLabels() { return actual.getLabels(); } @Override public GraphDatabaseService getGraphDatabase() { return ReadOnlyGraphDatabaseProxy.this; } @Override public Object getProperty( String key ) { return actual.getProperty( key ); } @Override public Object getProperty( String key, Object defaultValue ) { return actual.getProperty( key, defaultValue ); } @Override public Iterable<String> getPropertyKeys() { return actual.getPropertyKeys(); } @Override public boolean hasProperty( String key ) { return actual.hasProperty( key ); } @Override public Object removeProperty( String key ) { return readOnly(); } @Override public void setProperty( String key, Object value ) { readOnly(); } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_ReadOnlyGraphDatabaseProxy.java
1,533
class ReadOnlyNodeIndexProxy extends ReadOnlyIndexProxy<Node, Index<Node>> { ReadOnlyNodeIndexProxy( Index<Node> actual ) { super( actual ); } @Override Node wrap( Node actual ) { return readOnly( actual ); } @Override public String getName() { return actual.getName(); } @Override public Class<Node> getEntityType() { return Node.class; } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_ReadOnlyGraphDatabaseProxy.java
1,534
abstract class ReadOnlyIndexProxy<T extends PropertyContainer, I extends Index<T>> implements Index<T> { final I actual; ReadOnlyIndexProxy( I actual ) { this.actual = actual; } abstract T wrap( T actual ); @Override public void delete() { readOnly(); } @Override public void add( T entity, String key, Object value ) { readOnly(); } @Override public T putIfAbsent( T entity, String key, Object value ) { readOnly(); return null; } @Override public IndexHits<T> get( String key, Object value ) { return new ReadOnlyIndexHitsProxy<T>( this, actual.get( key, value ) ); } @Override public IndexHits<T> query( String key, Object queryOrQueryObject ) { return new ReadOnlyIndexHitsProxy<T>( this, actual.query( key, queryOrQueryObject ) ); } @Override public IndexHits<T> query( Object queryOrQueryObject ) { return new ReadOnlyIndexHitsProxy<T>( this, actual.query( queryOrQueryObject ) ); } @Override public void remove( T entity, String key, Object value ) { readOnly(); } @Override public void remove( T entity, String key ) { readOnly(); } @Override public void remove( T entity ) { readOnly(); } @Override public boolean isWriteable() { return false; } @Override public GraphDatabaseService getGraphDatabase() { return actual.getGraphDatabase(); } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_ReadOnlyGraphDatabaseProxy.java
1,535
private static class ReadOnlyIndexHitsProxy<T extends PropertyContainer> implements IndexHits<T> { private final ReadOnlyIndexProxy<T, ?> index; private final IndexHits<T> actual; ReadOnlyIndexHitsProxy( ReadOnlyIndexProxy<T, ?> index, IndexHits<T> actual ) { this.index = index; this.actual = actual; } @Override public void close() { actual.close(); } @Override public T getSingle() { return index.wrap( actual.getSingle() ); } @Override public int size() { return actual.size(); } @Override public boolean hasNext() { return actual.hasNext(); } @Override public T next() { return index.wrap( actual.next() ); } @Override public void remove() { readOnly(); } @Override public ResourceIterator<T> iterator() { return this; } @Override public float currentScore() { return actual.currentScore(); } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_ReadOnlyGraphDatabaseProxy.java
1,536
{ @Override protected Relationship underlyingObjectToObject( Relationship relationship ) { return new ReadOnlyRelationshipProxy( relationship ); } };
false
community_shell_src_main_java_org_neo4j_shell_kernel_ReadOnlyGraphDatabaseProxy.java
1,537
{ @Override protected Node underlyingObjectToObject( Node node ) { return new ReadOnlyNodeProxy( node ); } };
false
community_shell_src_main_java_org_neo4j_shell_kernel_ReadOnlyGraphDatabaseProxy.java
1,538
public class ReadOnlyGraphDatabaseProxy implements GraphDatabaseService, GraphDatabaseAPI, IndexManager { private final GraphDatabaseAPI actual; public ReadOnlyGraphDatabaseProxy( GraphDatabaseAPI graphDb ) { this.actual = graphDb; } public Node readOnly( Node actual ) { return new ReadOnlyNodeProxy( actual ); } public Relationship readOnly( Relationship actual ) { return new ReadOnlyRelationshipProxy( actual ); } private static <T> T readOnly() { throw readOnlyException(); } private static UnsupportedOperationException readOnlyException() { return new UnsupportedOperationException( "Read only Graph Database!" ); } @Override public Transaction beginTx() { return actual.beginTx(); } @Override public Node createNode() { return readOnly(); } @Override public Node createNode( Label... labels ) { return readOnly(); } public boolean enableRemoteShell() { throw new UnsupportedOperationException( "Cannot enable Remote Shell from Remote Shell" ); } public boolean enableRemoteShell( Map<String, Serializable> initialProperties ) { return enableRemoteShell(); } @Override public Iterable<Node> getAllNodes() { return nodes( actual.getAllNodes() ); } @Override public Node getNodeById( long id ) { return new ReadOnlyNodeProxy( actual.getNodeById( id ) ); } @Override public Relationship getRelationshipById( long id ) { return new ReadOnlyRelationshipProxy( actual.getRelationshipById( id ) ); } @Override public Iterable<RelationshipType> getRelationshipTypes() { return actual.getRelationshipTypes(); } @Override public KernelEventHandler registerKernelEventHandler( KernelEventHandler handler ) { return readOnly(); } @Override public <T> TransactionEventHandler<T> registerTransactionEventHandler( TransactionEventHandler<T> handler ) { return readOnly(); } @Override public boolean isAvailable( long timeout ) { return actual.isAvailable( timeout ); } @Override public void shutdown() { actual.shutdown(); } @Override public KernelEventHandler unregisterKernelEventHandler( KernelEventHandler handler ) { return readOnly(); } @Override public Schema schema() { return new ReadOnlySchemaProxy( actual.schema() ); } @Override public <T> TransactionEventHandler<T> unregisterTransactionEventHandler( TransactionEventHandler<T> handler ) { return readOnly(); } private class ReadOnlyNodeProxy implements Node { private final Node actual; ReadOnlyNodeProxy( Node actual ) { this.actual = actual; } @Override public int hashCode() { return actual.hashCode(); } @Override public boolean equals( Object obj ) { return (obj instanceof Node) && ((Node) obj).getId() == getId(); } @Override public String toString() { return actual.toString(); } @Override public long getId() { return actual.getId(); } @Override public Relationship createRelationshipTo( Node otherNode, RelationshipType type ) { return readOnly(); } @Override public void delete() { readOnly(); } @Override public Iterable<Relationship> getRelationships() { return relationships( actual.getRelationships() ); } @Override public Iterable<Relationship> getRelationships( RelationshipType... types ) { return relationships( actual.getRelationships( types ) ); } @Override public Iterable<Relationship> getRelationships( Direction direction, RelationshipType... types ) { return relationships( actual.getRelationships( direction, types ) ); } @Override public Iterable<Relationship> getRelationships( Direction dir ) { return relationships( actual.getRelationships( dir ) ); } @Override public Iterable<Relationship> getRelationships( RelationshipType type, Direction dir ) { return relationships( actual.getRelationships( type, dir ) ); } @Override public Relationship getSingleRelationship( RelationshipType type, Direction dir ) { return new ReadOnlyRelationshipProxy( actual.getSingleRelationship( type, dir ) ); } @Override public boolean hasRelationship() { return actual.hasRelationship(); } @Override public boolean hasRelationship( RelationshipType... types ) { return actual.hasRelationship( types ); } @Override public boolean hasRelationship( Direction direction, RelationshipType... types ) { return actual.hasRelationship( direction, types ); } @Override public boolean hasRelationship( Direction dir ) { return actual.hasRelationship( dir ); } @Override public boolean hasRelationship( RelationshipType type, Direction dir ) { return actual.hasRelationship( type, dir ); } @Override public Traverser traverse( Order traversalOrder, StopEvaluator stopEvaluator, ReturnableEvaluator returnableEvaluator, RelationshipType relationshipType, Direction direction ) { return OldTraverserWrapper.traverse( this, traversalOrder, stopEvaluator, returnableEvaluator, relationshipType, direction ); } @Override public Traverser traverse( Order traversalOrder, StopEvaluator stopEvaluator, ReturnableEvaluator returnableEvaluator, RelationshipType firstRelationshipType, Direction firstDirection, RelationshipType secondRelationshipType, Direction secondDirection ) { return OldTraverserWrapper.traverse( this, traversalOrder, stopEvaluator, returnableEvaluator, firstRelationshipType, firstDirection, secondRelationshipType, secondDirection ); } @Override public Traverser traverse( Order traversalOrder, StopEvaluator stopEvaluator, ReturnableEvaluator returnableEvaluator, Object... relationshipTypesAndDirections ) { return OldTraverserWrapper.traverse( this, traversalOrder, stopEvaluator, returnableEvaluator, relationshipTypesAndDirections ); } @Override public void addLabel( Label label ) { readOnly(); } @Override public void removeLabel( Label label ) { readOnly(); } @Override public boolean hasLabel( Label label ) { return actual.hasLabel( label ); } @Override public Iterable<Label> getLabels() { return actual.getLabels(); } @Override public GraphDatabaseService getGraphDatabase() { return ReadOnlyGraphDatabaseProxy.this; } @Override public Object getProperty( String key ) { return actual.getProperty( key ); } @Override public Object getProperty( String key, Object defaultValue ) { return actual.getProperty( key, defaultValue ); } @Override public Iterable<String> getPropertyKeys() { return actual.getPropertyKeys(); } @Override public boolean hasProperty( String key ) { return actual.hasProperty( key ); } @Override public Object removeProperty( String key ) { return readOnly(); } @Override public void setProperty( String key, Object value ) { readOnly(); } } private class ReadOnlyRelationshipProxy implements Relationship { private final Relationship actual; ReadOnlyRelationshipProxy( Relationship actual ) { this.actual = actual; } @Override public int hashCode() { return actual.hashCode(); } @Override public boolean equals( Object obj ) { return (obj instanceof Relationship) && ((Relationship) obj).getId() == getId(); } @Override public String toString() { return actual.toString(); } @Override public long getId() { return actual.getId(); } @Override public void delete() { readOnly(); } @Override public Node getEndNode() { return new ReadOnlyNodeProxy( actual.getEndNode() ); } @Override public Node[] getNodes() { return new Node[]{getStartNode(), getEndNode()}; } @Override public Node getOtherNode( Node node ) { return new ReadOnlyNodeProxy( actual.getOtherNode( node ) ); } @Override public Node getStartNode() { return new ReadOnlyNodeProxy( actual.getStartNode() ); } @Override public RelationshipType getType() { return actual.getType(); } @Override public boolean isType( RelationshipType type ) { return actual.isType( type ); } @Override public GraphDatabaseService getGraphDatabase() { return ReadOnlyGraphDatabaseProxy.this; } @Override public Object getProperty( String key ) { return actual.getProperty( key ); } @Override public Object getProperty( String key, Object defaultValue ) { return actual.getProperty( key, defaultValue ); } @Override public Iterable<String> getPropertyKeys() { return actual.getPropertyKeys(); } @Override public boolean hasProperty( String key ) { return actual.hasProperty( key ); } @Override public Object removeProperty( String key ) { return readOnly(); } @Override public void setProperty( String key, Object value ) { readOnly(); } } public Iterable<Node> nodes( Iterable<Node> nodes ) { return new IterableWrapper<Node, Node>( nodes ) { @Override protected Node underlyingObjectToObject( Node node ) { return new ReadOnlyNodeProxy( node ); } }; } public Iterable<Relationship> relationships( Iterable<Relationship> relationships ) { return new IterableWrapper<Relationship, Relationship>( relationships ) { @Override protected Relationship underlyingObjectToObject( Relationship relationship ) { return new ReadOnlyRelationshipProxy( relationship ); } }; } @Override public boolean existsForNodes( String indexName ) { return actual.index().existsForNodes( indexName ); } @Override public Index<Node> forNodes( String indexName ) { return new ReadOnlyNodeIndexProxy( actual.index().forNodes( indexName, null ) ); } @Override public Index<Node> forNodes( String indexName, Map<String, String> customConfiguration ) { return new ReadOnlyNodeIndexProxy( actual.index().forNodes( indexName, customConfiguration ) ); } @Override public String[] nodeIndexNames() { return actual.index().nodeIndexNames(); } @Override public boolean existsForRelationships( String indexName ) { return actual.index().existsForRelationships( indexName ); } @Override public RelationshipIndex forRelationships( String indexName ) { return new ReadOnlyRelationshipIndexProxy( actual.index().forRelationships( indexName, null ) ); } @Override public RelationshipIndex forRelationships( String indexName, Map<String, String> customConfiguration ) { return new ReadOnlyRelationshipIndexProxy( actual.index().forRelationships( indexName, customConfiguration ) ); } @Override public String[] relationshipIndexNames() { return actual.index().relationshipIndexNames(); } @Override public IndexManager index() { return this; } @Override public TraversalDescription traversalDescription() { return actual.traversalDescription(); } @Override public BidirectionalTraversalDescription bidirectionalTraversalDescription() { return actual.bidirectionalTraversalDescription(); } @Override public Map<String, String> getConfiguration( Index<? extends PropertyContainer> index ) { return actual.index().getConfiguration( index ); } @Override public String setConfiguration( Index<? extends PropertyContainer> index, String key, String value ) { throw new ReadOnlyDbException(); } @Override public String removeConfiguration( Index<? extends PropertyContainer> index, String key ) { throw new ReadOnlyDbException(); } @Override public AutoIndexer<Node> getNodeAutoIndexer() { return actual.index().getNodeAutoIndexer(); } @Override public RelationshipAutoIndexer getRelationshipAutoIndexer() { return actual.index().getRelationshipAutoIndexer(); } abstract class ReadOnlyIndexProxy<T extends PropertyContainer, I extends Index<T>> implements Index<T> { final I actual; ReadOnlyIndexProxy( I actual ) { this.actual = actual; } abstract T wrap( T actual ); @Override public void delete() { readOnly(); } @Override public void add( T entity, String key, Object value ) { readOnly(); } @Override public T putIfAbsent( T entity, String key, Object value ) { readOnly(); return null; } @Override public IndexHits<T> get( String key, Object value ) { return new ReadOnlyIndexHitsProxy<T>( this, actual.get( key, value ) ); } @Override public IndexHits<T> query( String key, Object queryOrQueryObject ) { return new ReadOnlyIndexHitsProxy<T>( this, actual.query( key, queryOrQueryObject ) ); } @Override public IndexHits<T> query( Object queryOrQueryObject ) { return new ReadOnlyIndexHitsProxy<T>( this, actual.query( queryOrQueryObject ) ); } @Override public void remove( T entity, String key, Object value ) { readOnly(); } @Override public void remove( T entity, String key ) { readOnly(); } @Override public void remove( T entity ) { readOnly(); } @Override public boolean isWriteable() { return false; } @Override public GraphDatabaseService getGraphDatabase() { return actual.getGraphDatabase(); } } class ReadOnlyNodeIndexProxy extends ReadOnlyIndexProxy<Node, Index<Node>> { ReadOnlyNodeIndexProxy( Index<Node> actual ) { super( actual ); } @Override Node wrap( Node actual ) { return readOnly( actual ); } @Override public String getName() { return actual.getName(); } @Override public Class<Node> getEntityType() { return Node.class; } } class ReadOnlyRelationshipIndexProxy extends ReadOnlyIndexProxy<Relationship, RelationshipIndex> implements RelationshipIndex { ReadOnlyRelationshipIndexProxy( RelationshipIndex actual ) { super( actual ); } @Override Relationship wrap( Relationship actual ) { return readOnly( actual ); } @Override public IndexHits<Relationship> get( String key, Object valueOrNull, Node startNodeOrNull, Node endNodeOrNull ) { return new ReadOnlyIndexHitsProxy<Relationship>( this, actual.get( key, valueOrNull, startNodeOrNull, endNodeOrNull ) ); } @Override public IndexHits<Relationship> query( String key, Object queryOrQueryObjectOrNull, Node startNodeOrNull, Node endNodeOrNull ) { return new ReadOnlyIndexHitsProxy<Relationship>( this, actual.query( key, queryOrQueryObjectOrNull, startNodeOrNull, endNodeOrNull ) ); } @Override public IndexHits<Relationship> query( Object queryOrQueryObjectOrNull, Node startNodeOrNull, Node endNodeOrNull ) { return new ReadOnlyIndexHitsProxy<Relationship>( this, actual.query( queryOrQueryObjectOrNull, startNodeOrNull, endNodeOrNull ) ); } @Override public String getName() { return actual.getName(); } @Override public Class<Relationship> getEntityType() { return Relationship.class; } } private static class ReadOnlyIndexHitsProxy<T extends PropertyContainer> implements IndexHits<T> { private final ReadOnlyIndexProxy<T, ?> index; private final IndexHits<T> actual; ReadOnlyIndexHitsProxy( ReadOnlyIndexProxy<T, ?> index, IndexHits<T> actual ) { this.index = index; this.actual = actual; } @Override public void close() { actual.close(); } @Override public T getSingle() { return index.wrap( actual.getSingle() ); } @Override public int size() { return actual.size(); } @Override public boolean hasNext() { return actual.hasNext(); } @Override public T next() { return index.wrap( actual.next() ); } @Override public void remove() { readOnly(); } @Override public ResourceIterator<T> iterator() { return this; } @Override public float currentScore() { return actual.currentScore(); } } private class ReadOnlySchemaProxy implements Schema { private final Schema actual; public ReadOnlySchemaProxy( Schema actual ) { this.actual = actual; } @Override public IndexCreator indexFor( Label label ) { throw readOnlyException(); } @Override public Iterable<IndexDefinition> getIndexes( Label label ) { return actual.getIndexes( label ); } @Override public Iterable<IndexDefinition> getIndexes() { return actual.getIndexes(); } @Override public IndexState getIndexState( IndexDefinition index ) { return actual.getIndexState( index ); } @Override public String getIndexFailure( IndexDefinition index ) { return actual.getIndexFailure( index ); } @Override public void awaitIndexOnline( IndexDefinition index, long duration, TimeUnit unit ) { actual.awaitIndexOnline( index, duration, unit ); } @Override public void awaitIndexesOnline( long duration, TimeUnit unit ) { actual.awaitIndexesOnline( duration, unit ); } @Override public ConstraintCreator constraintFor( Label label ) { throw readOnlyException(); } @Override public Iterable<ConstraintDefinition> getConstraints() { return actual.getConstraints(); } @Override public Iterable<ConstraintDefinition> getConstraints( Label label ) { return actual.getConstraints( label ); } } @Override public DependencyResolver getDependencyResolver() { return actual.getDependencyResolver(); } @Override public String getStoreDir() { return actual.getStoreDir(); } @Override public TransactionBuilder tx() { return actual.tx(); } @Override public StoreId storeId() { return actual.storeId(); } @Override public ResourceIterable<Node> findNodesByLabelAndProperty( Label label, String key, Object value ) { return actual.findNodesByLabelAndProperty( label, key, value ); } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_ReadOnlyGraphDatabaseProxy.java
1,539
public static class WorkingDirReplacer implements Replacer { @Override public String getReplacement( ShellServer server, Session session ) throws ShellException { try { return TransactionProvidingApp.getDisplayName( (GraphDatabaseShellServer) server, session, TransactionProvidingApp.getCurrent( (GraphDatabaseShellServer) server, session ), false ); } catch ( ShellException e ) { return TransactionProvidingApp.getDisplayNameForNonExistent(); } } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_GraphDatabaseShellServer.java
1,540
public class GraphDatabaseShellServer extends AbstractAppServer { private final GraphDatabaseAPI graphDb; private boolean graphDbCreatedHere; protected final Map<Serializable, Transaction> transactions = new ConcurrentHashMap<Serializable, Transaction>(); /** * @throws RemoteException if an RMI error occurs. */ public GraphDatabaseShellServer( String path, boolean readOnly, String configFileOrNull ) throws RemoteException { this( instantiateGraphDb( path, readOnly, configFileOrNull ), readOnly ); this.graphDbCreatedHere = true; } public GraphDatabaseShellServer( GraphDatabaseAPI graphDb ) throws RemoteException { this( graphDb, false ); } public GraphDatabaseShellServer( GraphDatabaseAPI graphDb, boolean readOnly ) throws RemoteException { super(); this.graphDb = readOnly ? new ReadOnlyGraphDatabaseProxy( graphDb ) : graphDb; this.bashInterpreter.addReplacer( "W", new WorkingDirReplacer() ); this.graphDbCreatedHere = false; } /* * Since we don't know which thread we might happen to run on, we can't trust transactions * to be stored in threads. Instead, we keep them around here, and suspend/resume in * transactions before apps get to run. */ @Override public Response interpretLine( Serializable clientId, String line, Output out ) throws ShellException { restoreTransaction( clientId ); try { return super.interpretLine( clientId, line, out ); } finally { saveTransaction( clientId ); } } private void saveTransaction( Serializable clientId ) throws ShellException { try { Transaction tx = getDb().getDependencyResolver().resolveDependency( TransactionManager.class ).suspend(); if ( tx == null ) { transactions.remove( clientId ); } else { transactions.put( clientId, tx ); } } catch ( Exception e ) { throw wrapException( e ); } } private void restoreTransaction( Serializable clientId ) throws ShellException { Transaction tx = transactions.get( clientId ); if ( tx != null ) { try { getDb().getDependencyResolver().resolveDependency( TransactionManager.class ).resume( tx ); } catch ( Exception e ) { throw wrapException( e ); } } } @Override protected void initialPopulateSession( Session session ) throws ShellException { session.set( Variables.TITLE_KEYS_KEY, ".*name.*,.*title.*" ); session.set( Variables.TITLE_MAX_LENGTH, "40" ); } @Override protected String getPrompt( Session session ) throws ShellException { try ( org.neo4j.graphdb.Transaction transaction = this.getDb().beginTx() ) { Object rawCustomPrompt = session.get( PROMPT_KEY ); String customPrompt = rawCustomPrompt != null ? rawCustomPrompt.toString() : getDefaultPrompt(); String output = bashInterpreter.interpret( customPrompt, this, session ); transaction.success(); return output; } } private static GraphDatabaseAPI instantiateGraphDb( String path, boolean readOnly, String configFileOrNull ) { GraphDatabaseBuilder builder = new GraphDatabaseFactory(). newEmbeddedDatabaseBuilder( path ). setConfig( GraphDatabaseSettings.read_only, Boolean.toString( readOnly ) ); if ( configFileOrNull != null ) { builder.loadPropertiesFromFile( configFileOrNull ); } return (GraphDatabaseAPI) builder.newGraphDatabase(); } @Override protected String getDefaultPrompt() { String name = "neo4j-sh"; if ( this.graphDb instanceof ReadOnlyGraphDatabaseProxy ) { name += "[readonly]"; } name += " \\W$ "; return name; } @Override protected String getWelcomeMessage() { return "Welcome to the Neo4j Shell! Enter 'help' for a list of commands"; } /** * @return the {@link GraphDatabaseAPI} instance given in the * constructor. */ public GraphDatabaseAPI getDb() { return this.graphDb; } /** * A {@link Replacer} for the variable "w"/"W" which returns the current * working directory (Bash), i.e. the current node. */ public static class WorkingDirReplacer implements Replacer { @Override public String getReplacement( ShellServer server, Session session ) throws ShellException { try { return TransactionProvidingApp.getDisplayName( (GraphDatabaseShellServer) server, session, TransactionProvidingApp.getCurrent( (GraphDatabaseShellServer) server, session ), false ); } catch ( ShellException e ) { return TransactionProvidingApp.getDisplayNameForNonExistent(); } } } @Override public void shutdown() throws RemoteException { if ( graphDbCreatedHere ) { this.graphDb.shutdown(); } super.shutdown(); } @Override public Welcome welcome( Map<String, Serializable> initialSession ) throws RemoteException, ShellException { try ( org.neo4j.graphdb.Transaction transaction = graphDb.beginTx() ) { Welcome welcome = super.welcome( initialSession ); transaction.success(); return welcome; } } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_GraphDatabaseShellServer.java
1,541
public class TestShellServerExtension extends KernelExtensionFactoryContractTest { public TestShellServerExtension() { super( ShellServerExtensionFactory.KEY, ShellServerExtensionFactory.class ); } @Override protected Map<String, String> configuration( boolean shouldLoad, int instance ) { Map<String, String> configuration = super.configuration( shouldLoad, instance ); if ( shouldLoad ) { configuration.put( ShellSettings.remote_shell_enabled.name(), Settings.TRUE ); configuration.put( ShellSettings.remote_shell_name.name(), "neo4j-shell-" + instance ); } return configuration; } }
false
community_shell_src_test_java_org_neo4j_shell_impl_TestShellServerExtension.java
1,542
public class SystemOutput implements Output { private PrintWriter out; public SystemOutput() { try { out = new PrintWriter(new OutputStreamWriter(System.out,"UTF-8")); } catch (UnsupportedEncodingException e) { System.err.println("Unsupported encoding UTF-8, using "+Charset.defaultCharset()+", error: "+e.getMessage()); out = new PrintWriter(new OutputStreamWriter(System.out, Charset.defaultCharset())); } } public void print( Serializable object ) { out.print(object); } public void println() { out.println(); out.flush(); } public void println( Serializable object ) { out.println( object ); out.flush(); } public Appendable append( char ch ) { this.print( ch ); return this; } public Appendable append( CharSequence sequence ) { this.println( RemoteOutput.asString( sequence ) ); return this; } public Appendable append( CharSequence sequence, int start, int end ) { this.print( RemoteOutput.asString( sequence ).substring( start, end ) ); return this; } }
false
community_shell_src_main_java_org_neo4j_shell_impl_SystemOutput.java
1,543
public class StandardConsole implements Console { private BufferedReader consoleReader; /** * Prints a formatted string to the console (System.out). * @param format the string/format to print. * @param args values used in conjunction with {@code format}. */ public void format( String format, Object... args ) { System.out.print( format ); } /** * @return the next line read from the console (user input). */ public String readLine( String prompt ) { try { format( prompt ); if ( consoleReader == null ) { consoleReader = new BufferedReader( new InputStreamReader( System.in, "UTF-8" ) ); } return consoleReader.readLine(); } catch ( IOException e ) { throw new RuntimeException( e ); } } }
false
community_shell_src_main_java_org_neo4j_shell_impl_StandardConsole.java
1,544
public abstract class SimpleAppServer implements ShellServer { private ShellServer remoteEndPoint; protected final BashVariableInterpreter bashInterpreter = new BashVariableInterpreter(); /** * The default RMI name for a shell server, * see {@link #makeRemotelyAvailable(int, String)}. */ public static final String DEFAULT_NAME = "shell"; /** * The default RMI port for a shell server, * see {@link #makeRemotelyAvailable(int, String)}. */ public static final int DEFAULT_PORT = 1337; private final Map<Serializable, Session> clientSessions = new ConcurrentHashMap<>(); private final AtomicInteger nextClientId = new AtomicInteger(); /** * Constructs a new server. * @throws RemoteException if an RMI exception occurs. */ public SimpleAppServer() throws RemoteException { super(); } @Override public String getName() { return DEFAULT_NAME; } @Override public Serializable interpretVariable( Serializable clientID, String key ) throws ShellException, RemoteException { return (Serializable) getClientSession( clientID ).get( key ); } protected Serializable newClientId() { return nextClientId.incrementAndGet(); } @Override public Welcome welcome( Map<String, Serializable> initialSession ) throws RemoteException, ShellException { Serializable clientId = newClientId(); if ( clientSessions.containsKey( clientId ) ) { throw new IllegalStateException( "Client " + clientId + " already initialized" ); } Session session = newSession( clientId, initialSession ); clientSessions.put( clientId, session ); try { String message = noWelcome( initialSession ) ? "" : getWelcomeMessage(); return new Welcome( message, clientId, getPrompt( session ) ); } catch ( ShellException e ) { throw new RemoteException( e.getMessage() ); } } private boolean noWelcome( Map<String, Serializable> initialSession ) { final Serializable quiet = initialSession.get( "quiet" ); if ( quiet == null ) { return false; } if ( quiet instanceof Boolean ) { return (Boolean) quiet; } return quiet.toString().equalsIgnoreCase( "true" ); } private Session newSession( Serializable id, Map<String, Serializable> initialSession ) throws ShellException { Session session = new Session( id ); initialPopulateSession( session ); for ( Map.Entry<String, Serializable> entry : initialSession.entrySet() ) { session.set( entry.getKey(), entry.getValue() ); } return session; } protected void initialPopulateSession( Session session ) throws ShellException { // No initial session by default } /** * Returns a prompt given a session, where the session may contain a custom "PS1" prompt variable. * * @param session the session to get custom prompt and other variables from. * @return the interpreted prompt to return to the client. */ protected abstract String getPrompt( Session session ) throws ShellException; protected String getDefaultPrompt() { return "sh$ "; } protected String getWelcomeMessage() { return "Welcome to the shell"; } public Session getClientSession( Serializable clientID ) { Session session = clientSessions.get( clientID ); if ( session == null ) { throw new IllegalStateException( "Client " + clientID + " not initialized" ); } return session; } @Override public void leave( Serializable clientID ) throws RemoteException { // TODO how about clients not properly leaving? if ( clientSessions.remove( clientID ) == null ) { throw new IllegalStateException( "Client " + clientID + " not initialized" ); } } @Override public synchronized void shutdown() throws RemoteException { if ( remoteEndPoint != null ) { remoteEndPoint.shutdown(); remoteEndPoint = null; } } @Override public synchronized void makeRemotelyAvailable( int port, String name ) throws RemoteException { remoteEndPoint().makeRemotelyAvailable( port, name ); } @Override public synchronized void makeRemotelyAvailable( String host, int port, String name ) throws RemoteException { remoteEndPoint().makeRemotelyAvailable( host, port, name ); } private ShellServer remoteEndPoint() throws RemoteException { if ( remoteEndPoint == null ) { remoteEndPoint = new RemotelyAvailableServer( this ); } return remoteEndPoint; } @Override public String[] getAllAvailableCommands() { return new String[0]; } public TabCompletion tabComplete( String partOfLine, Session session ) { return new TabCompletion( Collections.<String>emptyList(), 0 ); } @Override public void setSessionVariable( Serializable clientID, String key, Object value ) throws ShellException { getClientSession( clientID ).set( key, value ); } }
false
community_shell_src_main_java_org_neo4j_shell_impl_SimpleAppServer.java
1,545
@SuppressWarnings("UnusedDeclaration") /** * This class is instantiated by reflection (in {@link JLineConsole#newConsoleOrNullIfNotFound}) in order to ensure * that there is no hard dependency on jLine and the console can run in degraded form without it. */ class ShellTabCompletor implements Completor { private final ShellClient client; private long timeWhenCached; private Completor appNameCompletor; public ShellTabCompletor( ShellClient client ) { this.client = client; } public int complete( String buffer, int cursor, List candidates ) { if ( buffer == null || buffer.length() == 0 ) { return cursor; } try { if ( buffer.contains( " " ) ) { TabCompletion completion = client.getServer().tabComplete( client.getId(), buffer.trim() ); cursor = completion.getCursor(); //noinspection unchecked candidates.addAll( completion.getCandidates() ); } else { // Complete the app name return getAppNameCompletor().complete( buffer, cursor, candidates ); } } catch ( RemoteException e ) { // TODO Throw something? e.printStackTrace(); } catch ( ShellException e ) { // TODO Throw something? e.printStackTrace(); } return cursor; } private Completor getAppNameCompletor() throws RemoteException { if ( timeWhenCached != client.timeForMostRecentConnection() ) { timeWhenCached = client.timeForMostRecentConnection(); appNameCompletor = new SimpleCompletor( client.getServer().getAllAvailableCommands() ); } return this.appNameCompletor; } }
false
community_shell_src_main_java_org_neo4j_shell_impl_ShellTabCompletor.java
1,546
public abstract class ScriptExecutor { protected abstract String getPathKey(); protected String getDefaultPaths() { return ".:src:src" + File.separator + "script"; } /** * Executes a groovy script (with arguments) defined in {@code line}. * @param line the line which defines the groovy script with arguments. * @param session the {@link Session} to include as argument in groovy. * @param out the {@link Output} to include as argument in groovy. * @throws ShellException if the execution of a groovy script fails. */ public void execute( String line, Session session, Output out ) throws Exception { this.ensureDependenciesAreInClasspath(); if ( line == null || line.trim().length() == 0 ) { return; } List<String> pathList = this.getEnvPaths( session ); String[] paths = pathList.toArray( new String[ pathList.size() ] ); Object interpreter = this.newInterpreter( paths ); Map<String, Object> properties = new HashMap<String, Object>(); properties.put( "out", out ); properties.put( "session", session ); this.runScripts( interpreter, properties, line, paths ); } private void runScripts( Object interpreter, Map<String, Object> properties, String line, String[] paths ) throws Exception { ArgReader reader = new ArgReader( tokenizeStringWithQuotes( line ) ); while ( reader.hasNext() ) { String arg = reader.next(); if ( arg.startsWith( "--" ) ) { String[] scriptArgs = getScriptArgs( reader ); String scriptName = arg.substring( 2 ); Map<String, Object> props = new HashMap<String, Object>( properties ); props.put( "args", scriptArgs ); this.runScript( interpreter, scriptName, props, paths ); } } } protected abstract void runScript( Object interpreter, String scriptName, Map<String, Object> properties, String[] paths ) throws Exception; protected String findProperMessage( Throwable e ) { String message = e.toString(); if ( e.getCause() != null ) { message = this.findProperMessage( e.getCause() ); } return message; } private String[] getScriptArgs( ArgReader reader ) { reader.mark(); try { ArrayList<String> list = new ArrayList<String>(); while ( reader.hasNext() ) { String arg = reader.next(); if ( arg.startsWith( "--" ) ) { break; } list.add( arg ); reader.mark(); } return list.toArray( new String[ list.size() ] ); } finally { reader.flip(); } } private List<String> getEnvPaths( Session session ) throws ShellException { List<String> list = new ArrayList<String>(); collectPaths( list, ( String ) session.get( getPathKey() ) ); collectPaths( list, getDefaultPaths() ); return list; } private void collectPaths( List<String> paths, String pathString ) { if ( pathString != null && pathString.trim().length() > 0 ) { for ( String path : pathString.split( ":" ) ) { paths.add( path ); } } } protected abstract Object newInterpreter( String[] paths ) throws Exception; protected abstract void ensureDependenciesAreInClasspath() throws Exception; static class ArgReader implements Iterator<String> { private static final int START_INDEX = -1; private int index = START_INDEX; private final String[] args; private Integer mark; ArgReader( String[] args ) { this.args = args; } @Override public boolean hasNext() { return this.index + 1 < this.args.length; } @Override public String next() { if ( !hasNext() ) { throw new NoSuchElementException(); } this.index++; return this.args[ this.index ]; } /** * Goes to the previous argument. */ public void previous() { this.index--; if ( this.index < START_INDEX ) { this.index = START_INDEX; } } @Override public void remove() { throw new UnsupportedOperationException(); } /** * Marks the position so that a call to {@link #flip()} returns to that * position. */ public void mark() { this.mark = this.index; } /** * Flips back to the position defined in {@link #mark()}. */ public void flip() { if ( this.mark == null ) { throw new IllegalStateException(); } this.index = this.mark; this.mark = null; } } }
false
community_shell_src_main_java_org_neo4j_shell_apps_extra_ScriptExecutor.java
1,547
private static class OutputWriter extends Writer { private Output out; OutputWriter( Output out ) { this.out = out; } @Override public Writer append( char c ) throws IOException { out.append( c ); return this; } @Override public Writer append( CharSequence csq, int start, int end ) throws IOException { out.append( csq, start, end ); return this; } @Override public Writer append( CharSequence csq ) throws IOException { out.append( csq ); return this; } @Override public void close() throws IOException { } @Override public void flush() throws IOException { } @Override public void write( char[] cbuf, int off, int len ) throws IOException { out.print( new String( cbuf, off, len ) ); } @Override public void write( char[] cbuf ) throws IOException { out.print( new String( cbuf ) ); } @Override public void write( int c ) throws IOException { out.print( String.valueOf( c ) ); } @Override public void write( String str, int off, int len ) throws IOException { char[] cbuf = new char[ len ]; str.getChars( off, off + len, cbuf, 0 ); write( cbuf, off, len ); } @Override public void write( String str ) throws IOException { out.print( str ); } }
false
community_shell_src_main_java_org_neo4j_shell_apps_extra_JshExecutor.java
1,548
@Service.Implementation(App.class) public class Commit extends NonTransactionProvidingApp { @Override public String getDescription() { return "Commits a transaction"; } private Transaction getCurrectTransaction() throws ShellException { try { return getServer().getDb().getDependencyResolver().resolveDependency( TransactionManager.class ).getTransaction(); } catch ( SystemException e ) { throw wrapCause( e ); } } @Override protected Continuation exec( AppCommandParser parser, Session session, Output out ) throws ShellException, RemoteException { if ( parser.getLineWithoutApp().trim().length() > 0 ) { out.println( "Error: COMMIT should be run without trailing arguments" ); return Continuation.INPUT_COMPLETE; } Integer txCount = session.getCommitCount(); Transaction tx = getCurrectTransaction(); if ( txCount == null || txCount.equals( 0 ) ) { if ( tx != null ) { out.println( "Warning: committing a transaction not started by the shell" ); txCount = 1; } else { throw new ShellException( "Not in a transaction" ); } } if ( txCount.equals( 1 ) ) { if ( tx == null ) { throw fail( session, "Not in a transaction" ); } try { tx.commit(); session.remove( Variables.TX_COUNT ); out.println( "Transaction committed" ); return Continuation.INPUT_COMPLETE; } catch ( Exception e ) { throw fail( session, e.getMessage() ); } } else { session.set( Variables.TX_COUNT, --txCount ); out.println( String.format( "Nested transaction committed (Tx count: %d)", txCount ) ); return Continuation.INPUT_COMPLETE; } } public static ShellException fail( Session session, String message ) throws ShellException { session.remove( Variables.TX_COUNT ); return new ShellException( message ); } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_Commit.java
1,549
public class TestConfiguration { private GraphDatabaseService db; private ShellClient client; @Before public void before() throws Exception { db = new TestGraphDatabaseFactory() .newImpermanentDatabaseBuilder() .setConfig( "enable_remote_shell", "true" ) .newGraphDatabase(); client = new RemoteClient( NO_INITIAL_SESSION, remoteLocation(), new CollectingOutput() ); } @After public void after() throws Exception { client.shutdown(); db.shutdown(); } @Test public void deprecatedConfigName() throws Exception { CollectingOutput output = new CollectingOutput(); client.evaluate( "pwd", output ); assertTrue( output.asString().contains( "(?)" ) ); } }
false
community_shell_src_test_java_org_neo4j_shell_TestConfiguration.java
1,550
public class TestApps extends AbstractShellTest { // TODO: FIX THIS BEFORE MERGE @Test @Ignore("I don't get how pwd is supposed to work, and subsequently don't grok how to fix this test.") public void variationsOfCdAndPws() throws Exception { Relationship[] relationships = createRelationshipChain( 3 ); executeCommand( "mknode --cd" ); executeCommand( "pwd", pwdOutputFor( getStartNode( relationships[0] ) ) ); executeCommandExpectingException( "cd " + getStartNode( relationships[0] ).getId(), "stand" ); executeCommand( "pwd", pwdOutputFor( getStartNode( relationships[0] ) ) ); executeCommand( "cd " + getEndNode( relationships[0] ).getId() ); executeCommand( "pwd", pwdOutputFor( getStartNode( relationships[0] ), getEndNode( relationships[0] ) ) ); executeCommandExpectingException( "cd " + getEndNode( relationships[2] ).getId(), "connected" ); executeCommand( "pwd", pwdOutputFor( getStartNode( relationships[0] ), getEndNode( relationships[0] ) ) ); executeCommand( "cd -a " + getEndNode( relationships[2] ).getId() ); executeCommand( "pwd", pwdOutputFor( getStartNode( relationships[0] ), getEndNode( relationships[0] ), getEndNode( relationships[2] ) ) ); executeCommand( "cd .." ); executeCommand( "pwd", pwdOutputFor( getStartNode( relationships[0] ), getEndNode( relationships[0] ) ) ); executeCommand( "cd " + getEndNode( relationships[1] ).getId() ); executeCommand( "pwd", pwdOutputFor( getStartNode( relationships[0] ), getEndNode( relationships[0] ), getEndNode( relationships[1] ) ) ); } @Test public void canSetPropertiesAndLsWithFilters() throws Exception { RelationshipType type1 = DynamicRelationshipType.withName( "KNOWS" ); RelationshipType type2 = DynamicRelationshipType.withName( "LOVES" ); Relationship[] relationships = createRelationshipChain( type1, 2 ); Node node = getEndNode( relationships[0] ); createRelationshipChain( node, type2, 1 ); executeCommand( "cd " + node.getId() ); executeCommand( "ls", "<-", "->" ); executeCommand( "ls -p", "!Neo" ); setProperty( node, "name", "Neo" ); executeCommand( "ls -p", "Neo" ); executeCommand( "ls", "<-", "->", "Neo", type1.name(), type2.name() ); executeCommand( "ls -r", "<-", "->", "!Neo" ); executeCommand( "ls -rf .*:out", "!<-", "->", "!Neo", type1.name(), type2.name() ); executeCommand( "ls -rf .*:in", "<-", "!->", "!Neo", type1.name(), "!" + type2.name() ); executeCommand( "ls -rf KN.*:in", "<-", "!->", type1.name(), "!" + type2.name() ); executeCommand( "ls -rf LOVES:in", "!<-", "!->", "!" + type1.name(), "!" + type2.name() ); executeCommand( "ls -pf something", "!<-", "!->", "!Neo" ); executeCommand( "ls -pf name", "!<-", "!->", "Neo" ); executeCommand( "ls -pf name:Something", "!<-", "!->", "!Neo" ); executeCommand( "ls -pf name:Neo", "!<-", "!->", "Neo" ); } @Test public void canSetAndRemoveProperties() throws Exception { Relationship[] relationships = createRelationshipChain( 2 ); Node node = getEndNode( relationships[0] ); executeCommand( "cd " + node.getId() ); String name = "Mattias"; executeCommand( "set name " + name ); int age = 31; executeCommand( "set age -t int " + age ); executeCommand( "set \"some property\" -t long[] \"[1234,5678]" ); assertThat( node, inTx( db, hasProperty( "name" ).withValue( name ) ) ); assertThat( node, inTx( db, hasProperty( "age" ).withValue( age ) ) ); assertThat( node, inTx( db, hasProperty( "some property" ).withValue( new long[]{1234L, 5678L} ) ) ); executeCommand( "rm age" ); assertThat( node, inTx( db, not( hasProperty( "age" ) ) ) ); assertThat( node, inTx( db, hasProperty( "name" ).withValue( name ) ) ); } @Test public void canCreateRelationshipsAndNodes() throws Exception { RelationshipType type1 = withName( "type1" ); RelationshipType type2 = withName( "type2" ); RelationshipType type3 = withName( "type3" ); executeCommand( "mknode --cd" ); // No type supplied executeCommandExpectingException( "mkrel -c", "type" ); executeCommand( "mkrel -ct " + type1.name() ); Node node; try ( Transaction ignored = db.beginTx() ) { Relationship relationship = db.getNodeById( 0 ).getSingleRelationship( type1, Direction.OUTGOING ); node = relationship.getEndNode(); } executeCommand( "mkrel -t " + type2.name() + " " + node.getId() ); try ( Transaction ignored = db.beginTx() ) { Relationship otherRelationship = db.getNodeById( 0 ).getSingleRelationship( type2, Direction.OUTGOING ); assertEquals( node, otherRelationship.getEndNode() ); } // With properties executeCommand( "mkrel -ct " + type3.name() + " --np \"{'name':'Neo','destiny':'The one'}\" --rp \"{'number':11}\"" ); Node thirdNode; Relationship thirdRelationship; try ( Transaction ignored = db.beginTx() ) { thirdRelationship = db.getNodeById( 0 ).getSingleRelationship( type3, Direction.OUTGOING ); assertThat( thirdRelationship, inTx( db, hasProperty( "number" ).withValue( 11 ) ) ); thirdNode = thirdRelationship.getEndNode(); } assertThat( thirdNode, inTx( db, hasProperty( "name" ).withValue( "Neo" ) ) ); assertThat( thirdNode, inTx( db, hasProperty( "destiny" ).withValue( "The one" ) ) ); executeCommand( "cd -r " + thirdRelationship.getId() ); executeCommand( "mv number other-number" ); assertThat( thirdRelationship, inTx( db, not( hasProperty( "number" ) ) ) ); assertThat( thirdRelationship, inTx( db, hasProperty( "other-number" ).withValue( 11 ) ) ); // Create and go to executeCommand( "cd end" ); executeCommand( "mkrel -ct " + type1.name() + " --np \"{'name':'new'}\" --cd" ); executeCommand( "ls -p", "name", "new" ); } @Test public void rmrelCanLeaveStrandedIslands() throws Exception { Relationship[] relationships = createRelationshipChain( 4 ); executeCommand( "cd -a " + getEndNode( relationships[1] ).getId() ); Relationship relToDelete = relationships[2]; Node otherNode = getEndNode( relToDelete ); executeCommand( "rmrel -fd " + relToDelete.getId() ); assertRelationshipDoesntExist( relToDelete ); assertNodeExists( otherNode ); } @Test public void rmrelCanLeaveStrandedNodes() throws Exception { Relationship[] relationships = createRelationshipChain( 1 ); Node otherNode = getEndNode( relationships[0] ); executeCommand( "cd 0" ); executeCommand( "rmrel -f " + relationships[0].getId() ); assertRelationshipDoesntExist( relationships[0] ); assertNodeExists( otherNode ); } @Test public void rmrelCanDeleteStrandedNodes() throws Exception { Relationship[] relationships = createRelationshipChain( 1 ); Node otherNode = getEndNode( relationships[0] ); executeCommand( "cd 0" ); executeCommand( "rmrel -fd " + relationships[0].getId(), "not having any relationships" ); assertRelationshipDoesntExist( relationships[0] ); assertNodeDoesntExist( otherNode ); } @Test public void rmrelCanDeleteRelationshipSoThatCurrentNodeGetsStranded() throws Exception { Relationship[] relationships = createRelationshipChain( 2 ); executeCommand( "cd " + getEndNode( relationships[0] ).getId() ); deleteRelationship( relationships[0] ); Node currentNode = getStartNode( relationships[1] ); executeCommand( "rmrel -fd " + relationships[1].getId(), "not having any relationships" ); assertNodeExists( currentNode ); try ( Transaction ignored = db.beginTx() ) { assertFalse( currentNode.hasRelationship() ); } } private Node getStartNode( Relationship relationship ) { beginTx(); try { return relationship.getStartNode(); } finally { finishTx( false ); } } @Test public void rmnodeCanDeleteStrandedNodes() throws Exception { Relationship[] relationships = createRelationshipChain( 1 ); Node strandedNode = getEndNode( relationships[0] ); deleteRelationship( relationships[0] ); executeCommand( "rmnode " + strandedNode.getId() ); assertNodeDoesntExist( strandedNode ); } @Test public void rmnodeCanDeleteConnectedNodes() throws Exception { Relationship[] relationships = createRelationshipChain( 2 ); Node middleNode = getEndNode( relationships[0] ); executeCommandExpectingException( "rmnode " + middleNode.getId(), "still has relationships" ); assertNodeExists( middleNode ); Node endNode = getEndNode( relationships[1] ); executeCommand( "rmnode -f " + middleNode.getId(), "deleted" ); assertNodeDoesntExist( middleNode ); assertRelationshipDoesntExist( relationships[0] ); assertRelationshipDoesntExist( relationships[1] ); assertNodeExists( endNode ); executeCommand( "cd -a " + endNode.getId() ); executeCommand( "rmnode " + endNode.getId() ); executeCommand( "pwd", Pattern.quote( "(?)" ) ); } private Node getEndNode( Relationship relationship ) { beginTx(); try { return relationship.getEndNode(); } finally { finishTx( false ); } } @Test public void pwdWorksOnDeletedNode() throws Exception { Relationship[] relationships = createRelationshipChain( 1 ); executeCommand( "cd " + getEndNode( relationships[0] ).getId() ); // Delete the relationship and node we're standing on beginTx(); relationships[0].getEndNode().delete(); relationships[0].delete(); finishTx(); Relationship[] otherRelationships = createRelationshipChain( 1 ); executeCommand( "pwd", "Current is .+" ); executeCommand( "cd -a " + getEndNode( otherRelationships[0] ).getId() ); executeCommand( "ls" ); } @Test public void startEvenIfReferenceNodeHasBeenDeleted() throws Exception { Node node; try ( Transaction tx = db.beginTx() ) { node = db.createNode(); String name = "Test"; node.setProperty( "name", name ); tx.success(); } GraphDatabaseShellServer server = new GraphDatabaseShellServer( db ); ShellClient client = newShellClient( server ); executeCommand( client, "pwd", Pattern.quote( "(?)" ) ); executeCommand( client, "ls " + node.getId(), "Test" ); executeCommand( client, "cd -a " + node.getId() ); executeCommand( client, "ls", "Test" ); } @Test public void cypherWithSelfParameter() throws Exception { String nodeOneName = "Node ONE"; String name = "name"; String nodeTwoName = "Node TWO"; String relationshipName = "The relationship"; beginTx(); Node node = db.createNode(); node.setProperty( name, nodeOneName ); Node otherNode = db.createNode(); otherNode.setProperty( name, nodeTwoName ); Relationship relationship = node.createRelationshipTo( otherNode, RELATIONSHIP_TYPE ); relationship.setProperty( name, relationshipName ); Node strayNode = db.createNode(); finishTx(); executeCommand( "cd -a " + node.getId() ); executeCommand( "START n = node({self}) RETURN n.name;", nodeOneName ); executeCommand( "cd -r " + relationship.getId() ); executeCommand( "START r = relationship({self}) RETURN r.name;", relationshipName ); executeCommand( "cd " + otherNode.getId() ); executeCommand( "START n = node({self}) RETURN n.name;", nodeTwoName ); executeCommand( "cd -a " + strayNode.getId() ); beginTx(); strayNode.delete(); finishTx(); executeCommand( "START n = node(" + node.getId() + ") RETURN n.name;", nodeOneName ); } @Test public void cypherTiming() throws Exception { beginTx(); Node node = db.createNode(); Node otherNode = db.createNode(); node.createRelationshipTo( otherNode, RELATIONSHIP_TYPE ); finishTx(); executeCommand( "START n = node(" + node.getId() + ") optional match p=n-[r*]-m RETURN p;", "\\d+ ms" ); } @Test public void filterProperties() throws Exception { beginTx(); Node node = db.createNode(); node.setProperty( "name", "Mattias" ); node.setProperty( "blame", "Someone else" ); finishTx(); executeCommand( "cd -a " + node.getId() ); executeCommand( "ls", "Mattias" ); executeCommand( "ls -pf name", "Mattias", "!Someone else" ); executeCommand( "ls -f name", "Mattias", "!Someone else" ); executeCommand( "ls -f blame", "!Mattias", "Someone else" ); executeCommand( "ls -pf .*ame", "Mattias", "Someone else" ); executeCommand( "ls -f .*ame", "Mattias", "Someone else" ); } @Test public void createNewNode() throws Exception { executeCommand( "mknode --np \"{'name':'test'}\" --cd" ); executeCommand( "ls", "name", "test", "!-" /*no relationship*/ ); executeCommand( "mkrel -t KNOWS 0" ); executeCommand( "ls", "name", "test", "-", "KNOWS" ); } @Test public void createNodeWithArrayProperty() throws Exception { executeCommand( "mknode --np \"{'values':[1,2,3,4]}\" --cd" ); assertThat( getCurrentNode(), inTx( db, hasProperty( "values" ).withValue( new int[] {1,2,3,4} ) ) ); } @Test public void createNodeWithLabel() throws Exception { executeCommand( "mknode --cd -l Person" ); assertThat( getCurrentNode(), inTx( db, hasLabels( "Person" ) ) ); } @Test public void createNodeWithColonPrefixedLabel() throws Exception { executeCommand( "mknode --cd -l :Person" ); assertThat( getCurrentNode(), inTx( db, hasLabels( "Person" ) ) ); } @Test public void createNodeWithPropertiesAndLabels() throws Exception { executeCommand( "mknode --cd --np \"{'name': 'Test'}\" -l \"['Person', ':Thing']\"" ); assertThat( getCurrentNode(), inTx( db, hasProperty( "name" ).withValue( "Test" ) ) ); assertThat( getCurrentNode(), inTx( db, hasLabels( "Person", "Thing" ) ) ); } @Test public void createRelationshipWithArrayProperty() throws Exception { String type = "ARRAY"; executeCommand( "mknode --cd" ); executeCommand( "mkrel -ct " + type + " --rp \"{'values':[1,2,3,4]}\"" ); try ( Transaction ignored = db.beginTx() ) { assertThat( getCurrentNode().getSingleRelationship( withName( type ), OUTGOING ), inTx( db, hasProperty( "values" ).withValue( new int[]{1, 2, 3, 4} ) ) ); } } @Test public void createRelationshipToNewNodeWithLabels() throws Exception { String type = "TEST"; executeCommand( "mknode --cd" ); executeCommand( "mkrel -ctl " + type + " Person" ); try ( Transaction ignored = db.beginTx() ) { assertThat( getCurrentNode().getSingleRelationship( withName( type ), OUTGOING ).getEndNode(), inTx( db, hasLabels( "Person" ) ) ); } } @Test public void getDbinfo() throws Exception { // It's JSON coming back from dbinfo command executeCommand( "dbinfo -g Kernel", "\\{", "\\}", "StoreId" ); } @Test public void evalOneLinerExecutesImmediately() throws Exception { executeCommand( "eval db.createNode()", "Node\\[" ); } @Test public void evalMultiLineExecutesAfterAllLines() throws Exception { executeCommand( "eval\n" + "node = db.createNode()\n" + "node.setProperty( \"name\", \"Mattias\" )\n" + "node.getProperty( \"name\" )\n", "Mattias" ); } @Test public void canReassignShellVariables() throws Exception { executeCommand( "export a=10" ); executeCommand( "export b=a" ); executeCommand( "env", "a=10", "b=10" ); } @Test public void canSetVariableToMap() throws Exception { executeCommand( "export a={a:10}" ); executeCommand( "export b={\"b\":\"foo\"}" ); executeCommand( "env", "a=\\{a=10\\}", "b=\\{b=foo\\}" ); } @Test public void canSetVariableToScalars() throws Exception { executeCommand( "export a=true" ); executeCommand( "export b=100" ); executeCommand( "export c=\"foo\"" ); executeCommand( "env", "a=true", "b=100", "c=foo" ); } @Test public void canSetVariableToArray() throws Exception { executeCommand( "export a=[1,true,\"foo\"]" ); executeCommand( "env", "a=\\[1, true, foo\\]" ); } @Test public void canRemoveShellVariables() throws Exception { executeCommand( "export a=10" ); executeCommand( "export a=null" ); executeCommand( "env", "!a=10", "!a=null" ); } @Test public void canUseAlias() throws Exception { executeCommand( "alias x=pwd" ); executeCommand( "x", "Current is .+" ); } @Test public void cypherNodeStillHasRelationshipsException() throws Exception { // Given executeCommand( "create a,b,a-[:x]->b;" ); // When try { executeCommand( "start n=node(*) delete n;" ); fail( "Should have failed with " + NodeStillHasRelationshipsException.class.getName() + " exception" ); } catch ( ShellException e ) { // Then assertThat( e.getStackTraceAsString(), containsString( "still has relationships" ) ); } } @Test public void use_cypher_merge() throws Exception { executeCommand( "merge (n:Person {name:'Andres'});" ); assertThat( findNodesByLabelAndProperty( label( "Person" ), "name", "Andres", db ), hasSize( 1 ) ); } @Test public void canSetInitialSessionVariables() throws Exception { Map<String, Serializable> values = genericMap( "mykey", "myvalue", "my_other_key", "My other value" ); ShellClient client = newShellClient( shellServer, values ); String[] allStrings = new String[values.size()*2]; int i = 0; for ( Map.Entry<String, Serializable> entry : values.entrySet() ) { allStrings[i++] = entry.getKey(); allStrings[i++] = entry.getValue().toString(); } executeCommand( client, "env", allStrings ); } @Test public void canDisableWelcomeMessage() throws Exception { Map<String, Serializable> values = genericMap( "quiet", "true" ); final CollectingOutput out = new CollectingOutput(); ShellClient client = new SameJvmClient( values, shellServer, out ); client.shutdown(); final String outString = out.asString(); assertEquals( "Shows welcome message: " + outString, false, outString.contains( "Welcome to the Neo4j Shell! Enter 'help' for a list of commands" ) ); } @Test public void doesShowWelcomeMessage() throws Exception { Map<String, Serializable> values = genericMap(); final CollectingOutput out = new CollectingOutput(); ShellClient client = new SameJvmClient( values, shellServer, out ); client.shutdown(); final String outString = out.asString(); assertEquals( "Shows welcome message: " + outString, true, outString.contains( "Welcome to the Neo4j Shell! Enter 'help' for a list of commands" ) ); } @Test public void canExecuteCypherWithShellVariables() throws Exception { Map<String, Serializable> variables = genericMap( "id", 0 ); ShellClient client = newShellClient( shellServer, variables ); try ( Transaction tx = db.beginTx() ) { db.createNode(); tx.success(); } executeCommand( client, "start n=node({id}) return n;", "1 row" ); } @Test public void canDumpSubgraphWithCypher() throws Exception { final DynamicRelationshipType type = DynamicRelationshipType.withName( "KNOWS" ); beginTx(); createRelationshipChain( db.createNode(), type, 1 ); finishTx(); executeCommand( "dump start n=node(0) match n-[r]->m return n,r,m;", "begin", "create _0", "create \\(_1\\)", "_0-\\[:`KNOWS`\\]->_1", "commit" ); } @Test public void canDumpGraph() throws Exception { final DynamicRelationshipType type = DynamicRelationshipType.withName( "KNOWS" ); beginTx(); final Relationship rel = createRelationshipChain( db.createNode(), type, 1 )[0]; rel.getStartNode().setProperty( "f o o", "bar" ); rel.setProperty( "since", 2010 ); rel.getEndNode().setProperty( "flags", new Boolean[]{true, false, true} ); finishTx(); executeCommand( "dump ", "begin", "create \\(_0 \\{\\`f o o\\`:\"bar\"\\}\\)", "create \\(_1 \\{`flags`:\\[true, false, true\\]\\}\\)", "_0-\\[:`KNOWS` \\{`since`:2010\\}\\]->_1", "commit" ); } @Test public void commentsAreIgnored() throws Exception { executeCommand( "eval\n" + "// This comment should be ignored\n" + "node = db.createNode()\n" + "node.setProperty( \"name\", \"Mattias\" )\n" + "node.getProperty( \"name\" )\n", "Mattias" ); } @Test public void commentsAloneAreIgnored() throws Exception { // See GitHub issue #1204 executeCommand( "// a comment\n" ); } @Test public void canAddLabelToNode() throws Exception { // GIVEN Relationship[] chain = createRelationshipChain( 1 ); Node node = getEndNode( chain[0] ); executeCommand( "cd -a " + node.getId() ); // WHEN executeCommand( "set -l Person" ); // THEN assertThat( node, inTx( db, hasLabels( "Person" ) ) ); } @Test public void canAddMultipleLabelsToNode() throws Exception { // GIVEN Relationship[] chain = createRelationshipChain( 1 ); Node node = getEndNode( chain[0] ); executeCommand( "cd -a " + node.getId() ); // WHEN executeCommand( "set -l ['Person','Thing']" ); // THEN assertThat( node, inTx( db, hasLabels( "Person", "Thing" ) ) ); } @Test public void canRemoveLabelFromNode() throws Exception { // GIVEN beginTx(); Relationship[] chain = createRelationshipChain( 1 ); Node node = chain[0].getEndNode(); node.addLabel( label( "Person" ) ); node.addLabel( label( "Pilot" ) ); finishTx(); executeCommand( "cd -a " + node.getId() ); // WHEN executeCommand( "rm -l Person" ); // THEN assertThat( node, inTx( db, hasLabels( "Pilot" ) ) ); assertThat( node, inTx( db, not( hasLabels( "Person" ) ) ) ); } @Test public void canRemoveMultipleLabelsFromNode() throws Exception { // GIVEN beginTx(); Relationship[] chain = createRelationshipChain( 1 ); Node node = chain[0].getEndNode(); node.addLabel( label( "Person" ) ); node.addLabel( label( "Thing" ) ); node.addLabel( label( "Object" ) ); finishTx(); executeCommand( "cd -a " + node.getId() ); // WHEN executeCommand( "rm -l ['Person','Object']" ); // THEN assertThat( node, inTx( db, hasLabels( "Thing" ) ) ); assertThat( node, inTx( db, not( hasLabels( "Person", "Object" ) ) ) ); } @Test public void canListLabels() throws Exception { // GIVEN beginTx(); Relationship[] chain = createRelationshipChain( 1 ); Node node = chain[0].getEndNode(); node.addLabel( label( "Person" ) ); node.addLabel( label( "Father" ) ); finishTx(); executeCommand( "cd -a " + node.getId() ); // WHEN/THEN executeCommand( "ls", ":Person", ":Father" ); } @Test public void canListFilteredLabels() throws Exception { // GIVEN beginTx(); Relationship[] chain = createRelationshipChain( 1 ); Node node = chain[0].getEndNode(); node.addLabel( label( "Person" ) ); node.addLabel( label( "Father" ) ); finishTx(); executeCommand( "cd -a " + node.getId() ); // WHEN/THEN executeCommand( "ls -f Per.*", ":Person", "!:Father" ); } @Test public void canListIndexes() throws Exception { // GIVEN Label label = label( "Person" ); beginTx(); IndexDefinition index = db.schema().indexFor( label ).on( "name" ).create(); finishTx(); waitForIndex( db, index ); // WHEN / THEN executeCommand( "schema ls", ":Person", IndexState.ONLINE.name() ); } @Test public void canListIndexesForGivenLabel() throws Exception { // GIVEN Label label1 = label( "Person" ); Label label2 = label( "Building" ); beginTx(); IndexDefinition index1 = db.schema().indexFor( label1 ).on( "name" ).create(); IndexDefinition index2 = db.schema().indexFor( label2 ).on( "name" ).create(); finishTx(); waitForIndex( db, index1 ); waitForIndex( db, index2 ); // WHEN / THEN executeCommand( "schema ls -l " + label2.name(), ":" + label2.name(), IndexState.ONLINE.name(), "!:" + label1.name() ); } @Test public void canListIndexesForGivenPropertyAndLabel() throws Exception { // GIVEN Label label1 = label( "Person" ); Label label2 = label( "Thing" ); String property1 = "name"; String property2 = "age"; beginTx(); IndexDefinition index1 = db.schema().indexFor( label1 ).on( property1 ).create(); IndexDefinition index2 = db.schema().indexFor( label1 ).on( property2 ).create(); IndexDefinition index3 = db.schema().indexFor( label2 ).on( property1 ).create(); IndexDefinition index4 = db.schema().indexFor( label2 ).on( property2 ).create(); finishTx(); waitForIndex( db, index1 ); waitForIndex( db, index2 ); waitForIndex( db, index3 ); waitForIndex( db, index4 ); // WHEN / THEN executeCommand( "schema ls" + " -l :" + label2.name() + " -p " + property1, label2.name(), property1, "!" + label1.name(), "!" + property2 ); } @Test public void canAwaitIndexesToComeOnline() throws Exception { // GIVEN Label label = label( "Person" ); beginTx(); IndexDefinition index = db.schema().indexFor( label ).on( "name" ).create(); finishTx(); // WHEN / THEN executeCommand( "schema await -l " + label.name() ); beginTx(); assertEquals( IndexState.ONLINE, db.schema().getIndexState( index ) ); finishTx(); } @Test public void canListIndexesWhenNoOptionGiven() throws Exception { // GIVEN Label label = label( "Person" ); String property = "name"; beginTx(); IndexDefinition index = db.schema().indexFor( label ).on( property ).create(); finishTx(); waitForIndex( db, index ); // WHEN / THEN executeCommand( "schema", label.name(), property ); } @Test public void canListConstraints() throws Exception { // GIVEN Label label = label( "Person" ); beginTx(); db.schema().constraintFor( label ).assertPropertyIsUnique( "name" ).create(); finishTx(); // WHEN / THEN executeCommand( "schema ls", "ON \\(person:Person\\) ASSERT person.name IS UNIQUE" ); } @Test public void canListConstraintsByLabel() throws Exception { // GIVEN Label label1 = label( "Person" ); beginTx(); db.schema().constraintFor( label1 ).assertPropertyIsUnique( "name" ).create(); finishTx(); // WHEN / THEN executeCommand( "schema ls -l :Person", "ON \\(person:Person\\) ASSERT person.name IS UNIQUE" ); } @Test public void canListConstraintsByLabelAndProperty() throws Exception { // GIVEN Label label1 = label( "Person" ); beginTx(); db.schema().constraintFor( label1 ).assertPropertyIsUnique( "name" ).create(); finishTx(); // WHEN / THEN executeCommand( "schema ls -l :Person -p name", "ON \\(person:Person\\) ASSERT person.name IS UNIQUE" ); } @Test public void committingFailedTransactionShouldProperlyFinishTheTransaction() throws Exception { // GIVEN a transaction with a created constraint in it executeCommand( "begin" ); executeCommand( "create constraint on (node:Label1) assert node.key1 is unique;" ); // WHEN trying to do a data update try { executeCommand( "mknode --cd" ); fail( "Should have failed" ); } catch ( ShellException e ) { assertThat( e.getMessage(), containsString( ConstraintViolationException.class.getSimpleName() ) ); assertThat( e.getMessage(), containsString( "Cannot perform data updates" ) ); } // THEN the commit should fail afterwards try { executeCommand( "commit" ); fail( "Commit should fail" ); } catch ( ShellException e ) { assertThat( e.getMessage(), containsString( "rolled back" ) ); } // and also a rollback following it should fail try { executeCommand( "rollback" ); fail( "Rolling back at this point should fail since there's no transaction open" ); } catch ( ShellException e ) { assertThat( e.getMessage(), containsString( "Not in a transaction" ) ); } } @Test public void allowsArgumentsStartingWithSingleHyphensForCommandsThatDontTakeOptions() throws Exception { executeCommand( "CREATE (n { test : ' -0' });" ); } @Test public void allowsArgumentsStartingWithDoubldHyphensForCommandsThatDontTakeOptions() throws Exception { executeCommand( "MATCH () -- () RETURN 0;" ); } @Test public void shouldAllowQueriesToStartWithOptionalMatch() throws Exception { executeCommand( "OPTIONAL MATCH (n) RETURN n;" ); } @Test public void canListAllConfiguration() throws Exception { executeCommand( "dbinfo -g Configuration", "\"ephemeral\": \"true\"" ); } }
false
community_shell_src_test_java_org_neo4j_shell_TestApps.java
1,551
public class TabCompletion implements Serializable { private final Collection<String> candidates; private final int cursor; public TabCompletion( Collection<String> candidates, int cursor ) { this.candidates = candidates; this.cursor = cursor; } public Collection<String> getCandidates() { return candidates; } public int getCursor() { return cursor; } }
false
community_shell_src_main_java_org_neo4j_shell_TabCompletion.java
1,552
public class StartDbWithShell { public static void main( String[] args ) throws Exception { String path = args.length > 0 ? args[0] : "target/test-data/shell-db"; GraphDatabaseService db = new GraphDatabaseFactory(). newEmbeddedDatabaseBuilder( path ). setConfig( ShellSettings.remote_shell_enabled, Settings.TRUE). setConfig( GraphDatabaseSettings.allow_store_upgrade, Settings.TRUE). newGraphDatabase(); System.out.println( "db " + path + " started, ENTER to quit" ); ignore( System.in.read() ); db.shutdown(); } }
false
community_shell_src_test_java_org_neo4j_shell_StartDbWithShell.java
1,553
{ @Override protected void configure( GraphDatabaseBuilder builder ) { builder.setConfig( ShellSettings.remote_shell_enabled, Settings.TRUE ); } };
false
community_shell_src_test_java_org_neo4j_shell_StartClientTest.java
1,554
public class StartClientTest { @Rule public ImpermanentDatabaseRule db = new ImpermanentDatabaseRule() { @Override protected void configure( GraphDatabaseBuilder builder ) { builder.setConfig( ShellSettings.remote_shell_enabled, Settings.TRUE ); } }; @Test public void givenShellClientWhenOpenFileThenExecuteFileCommands() { // Given // an empty database // When StartClient.main(new String[]{"-file", getClass().getResource( "/testshell.txt" ).getFile()}); // Then try ( Transaction tx = db.getGraphDatabaseService().beginTx() ) { assertThat( (String) db.getGraphDatabaseService().getNodeById( 0 ).getProperty( "foo" ), equalTo( "bar" ) ); tx.success(); } } @Test public void givenShellClientWhenReadFromStdinThenExecutePipedCommands() throws IOException { // Given // an empty database // When InputStream realStdin = System.in; try { System.setIn( new ByteArrayInputStream( "CREATE (n {foo:'bar'});".getBytes() ) ); StartClient.main( new String[] { "-file", "-" } ); } finally { System.setIn( realStdin ); } // Then try ( Transaction tx = db.getGraphDatabaseService().beginTx() ) { assertThat( (String) db.getGraphDatabaseService().getNodeById( 0 ).getProperty( "foo" ), equalTo( "bar" ) ); tx.success(); } } @Test public void mustWarnWhenRunningScriptWithUnterminatedMultilineCommands() { // Given an empty database and the unterminated-cypher-query.txt file. String script = getClass().getResource( "/unterminated-cypher-query.txt" ).getFile(); // When running the script with -file String output = runAndCaptureOutput( new String[]{ "-file", script } ); // Then we should get a warning assertThat( output, containsString( AbstractClient.WARN_UNTERMINATED_INPUT ) ); } @Test public void mustNotAboutExitingWithUnterminatedCommandWhenItIsNothingButComments() { // Given an empty database and the unterminated-comment.txt file. String script = getClass().getResource( "/unterminated-comment.txt" ).getFile(); // When running the script with -file String output = runAndCaptureOutput( new String[]{ "-file", script } ); // Then we should get a warning assertThat( output, not( containsString( AbstractClient.WARN_UNTERMINATED_INPUT ) ) ); } private String runAndCaptureOutput( String[] arguments ) { ByteArrayOutputStream buf = new ByteArrayOutputStream(); PrintStream out = new PrintStream( buf ); PrintStream oldOut = System.out; System.setOut( out ); try { StartClient.main( arguments ); out.close(); return buf.toString(); } finally { System.setOut( oldOut ); } } }
false
community_shell_src_test_java_org_neo4j_shell_StartClientTest.java
1,555
{ @Override public void run() { shutdownIfNecessary( server ); } } );
false
community_shell_src_main_java_org_neo4j_shell_StartClient.java
1,556
public class StartClient { private AtomicBoolean hasBeenShutdown = new AtomicBoolean(); /** * The path to the local (this JVM) {@link GraphDatabaseService} to * start and connect to. */ public static final String ARG_PATH = "path"; /** * Whether or not the shell client should be readonly. */ public static final String ARG_READONLY = "readonly"; /** * The host (ip or name) to connect remotely to. */ public static final String ARG_HOST = "host"; /** * The port to connect remotely on. A server must have been started * on that port. */ public static final String ARG_PORT = "port"; /** * The RMI name to use. */ public static final String ARG_NAME = "name"; /** * The PID (process ID) to connect to. */ public static final String ARG_PID = "pid"; /** * Commands (a line can contain more than one command, with && in between) * to execute when the shell client has been connected. */ public static final String ARG_COMMAND = "c"; /** * File a file with shell commands to execute when the shell client has * been connected. */ public static final String ARG_FILE = "file"; /** * Special character used to request reading from stdin rather than a file. * Uses the dash character, which is a common way to specify this. */ public static final String ARG_FILE_STDIN = "-"; /** * Configuration file to load and use if a local {@link GraphDatabaseService} * is started in this JVM. */ public static final String ARG_CONFIG = "config"; private StartClient() { } /** * Starts a shell client. Remote or local depending on the arguments. * * @param arguments the arguments from the command line. Can contain * information about whether to start a local * {@link GraphDatabaseShellServer} or connect to an already running * {@link GraphDatabaseService}. */ public static void main( String[] arguments ) { new StartClient().start( arguments ); } private void start( String[] arguments ) { Args args = new Args( arguments ); if ( args.has( "?" ) || args.has( "h" ) || args.has( "help" ) || args.has( "usage" ) ) { printUsage(); return; } String path = args.get( ARG_PATH, null ); String host = args.get( ARG_HOST, null ); String port = args.get( ARG_PORT, null ); String name = args.get( ARG_NAME, null ); String pid = args.get( ARG_PID, null ); if ( (path != null && (port != null || name != null || host != null || pid != null)) || (pid != null && host != null) ) { System.err.println( "You have supplied both " + ARG_PATH + " as well as " + ARG_HOST + "/" + ARG_PORT + "/" + ARG_NAME + ". " + "You should either supply only " + ARG_PATH + " or " + ARG_HOST + "/" + ARG_PORT + "/" + ARG_NAME + " so that either a local or " + "remote shell client can be started" ); } // Local else if ( path != null ) { try { checkNeo4jDependency(); } catch ( ShellException e ) { handleException( e, args ); } startLocal( args ); } // Remote else { String readonly = args.get( ARG_READONLY, null ); if (readonly != null ) { System.err.println( "Warning: -" + ARG_READONLY + " is ignored unless you connect with -" + ARG_PATH + "!" ); } // Start server on the supplied process if ( pid != null ) { startServer( pid, args ); } startRemote( args ); } } private static final Method attachMethod, loadMethod; static { Method attach, load; try { Class<?> vmClass = Class.forName( "com.sun.tools.attach.VirtualMachine" ); attach = vmClass.getMethod( "attach", String.class ); load = vmClass.getMethod( "loadAgent", String.class, String.class ); } catch ( Exception e ) { attach = load = null; } attachMethod = attach; loadMethod = load; } private static void checkNeo4jDependency() throws ShellException { try { Class.forName( "org.neo4j.graphdb.GraphDatabaseService" ); } catch ( Exception e ) { throw new ShellException( "Neo4j not found on the classpath" ); } } private void startLocal( Args args ) { String dbPath = args.get( ARG_PATH, null ); if ( dbPath == null ) { System.err.println( "ERROR: To start a local Neo4j service and a " + "shell client on top of that you need to supply a path to a " + "Neo4j store or just a new path where a new store will " + "be created if it doesn't exist. -" + ARG_PATH + " /my/path/here" ); return; } try { boolean readOnly = args.getBoolean( ARG_READONLY, false, true ); tryStartLocalServerAndClient( dbPath, readOnly, args ); } catch ( Exception e ) { handleException( e, args ); } System.exit( 0 ); } private void tryStartLocalServerAndClient( String dbPath, boolean readOnly, Args args ) throws Exception { String configFile = args.get( ARG_CONFIG, null ); final GraphDatabaseShellServer server = new GraphDatabaseShellServer( dbPath, readOnly, configFile ); Runtime.getRuntime().addShutdownHook( new Thread() { @Override public void run() { shutdownIfNecessary( server ); } } ); if ( !isCommandLine( args ) ) { System.out.println( "NOTE: Local Neo4j graph database service at '" + dbPath + "'" ); } ShellClient client = ShellLobby.newClient( server, getSessionVariablesFromArgs( args ) ); grabPromptOrJustExecuteCommand( client, args ); shutdownIfNecessary( server ); } private void shutdownIfNecessary( ShellServer server ) { try { if ( !hasBeenShutdown.compareAndSet( false, true ) ) { server.shutdown(); } } catch ( RemoteException e ) { throw new RuntimeException( e ); } } private void startServer( String pid, Args args ) { String port = args.get( "port", Integer.toString( SimpleAppServer.DEFAULT_PORT ) ); String name = args.get( "name", SimpleAppServer.DEFAULT_NAME ); try { String jarfile = new File( getClass().getProtectionDomain().getCodeSource().getLocation().toURI() ).getAbsolutePath(); Object vm = attachMethod.invoke( null, pid ); loadMethod.invoke( vm, jarfile, new ShellBootstrap( Integer.parseInt( port ), name ).serialize() ); } catch ( Exception e ) { handleException( e, args ); } } private static void startRemote( Args args ) { try { String host = args.get( ARG_HOST, "localhost" ); int port = args.getNumber( ARG_PORT, SimpleAppServer.DEFAULT_PORT ).intValue(); String name = args.get( ARG_NAME, SimpleAppServer.DEFAULT_NAME ); ShellClient client = ShellLobby.newClient( RmiLocation.location( host, port, name ), getSessionVariablesFromArgs( args ) ); if ( !isCommandLine( args ) ) { System.out.println( "NOTE: Remote Neo4j graph database service '" + name + "' at port " + port ); } grabPromptOrJustExecuteCommand( client, args ); } catch ( Exception e ) { handleException( e, args ); } } private static boolean isCommandLine( Args args ) { return args.get( ARG_COMMAND, null ) != null || args.get( ARG_FILE, null ) != null; } private static void grabPromptOrJustExecuteCommand( ShellClient client, Args args ) throws Exception { String command = args.get( ARG_COMMAND, null ); if ( command != null ) { client.evaluate( command ); client.shutdown(); return; } String fileName = args.get( ARG_FILE, null ); if ( fileName != null ) { BufferedReader reader = null; try { if ( fileName.equals( ARG_FILE_STDIN ) ) { reader = new BufferedReader( new InputStreamReader( System.in, UTF_8 ) ); } else { File file = new File( fileName ); if ( !file.exists() ) { throw new ShellException( "File to execute " + "does not exist: " + fileName ); } reader = newBufferedFileReader( file, UTF_8 ); } executeCommandStream( client, reader ); } finally { if ( reader != null ) { reader.close(); } } return; } client.grabPrompt(); } private static void executeCommandStream( ShellClient client, BufferedReader reader ) throws IOException, ShellException { try { for ( String line; ( line = reader.readLine() ) != null; ) { client.evaluate( line ); } } finally { client.shutdown(); reader.close(); } } static Map<String, Serializable> getSessionVariablesFromArgs( Args args ) throws RemoteException, ShellException { String profile = args.get( "profile", null ); Map<String, Serializable> session = new HashMap<String, Serializable>(); if ( profile != null ) { applyProfileFile( new File( profile ), session ); } for ( Map.Entry<String, String> entry : args.asMap().entrySet() ) { String key = entry.getKey(); if ( key.startsWith( "D" ) ) { key = key.substring( 1 ); session.put( key, entry.getValue() ); } } if ( isCommandLine( args ) ) { session.put( "quiet", true ); } return session; } private static void applyProfileFile( File file, Map<String, Serializable> session ) throws ShellException { try (FileInputStream fis = new FileInputStream( file )) { Properties properties = new Properties(); properties.load( fis ); for ( Object key : properties.keySet() ) { String stringKey = (String) key; String value = properties.getProperty( stringKey ); session.put( stringKey, value ); } } catch ( IOException e ) { throw new IllegalArgumentException( "Couldn't find profile '" + file.getAbsolutePath() + "'" ); } } private static void handleException( Exception e, Args args ) { String message = e.getCause() instanceof ConnectException ? "Connection refused" : e.getMessage(); System.err.println( "ERROR (-v for expanded information):\n\t" + message ); if ( args.has( "v" ) ) { e.printStackTrace( System.err ); } System.err.println(); printUsage(); System.exit( 1 ); } private static int longestString( String... strings ) { int length = 0; for ( String string : strings ) { if ( string.length() > length ) { length = string.length(); } } return length; } private static void printUsage() { int port = SimpleAppServer.DEFAULT_PORT; String name = SimpleAppServer.DEFAULT_NAME; int longestArgLength = longestString( ARG_FILE, ARG_COMMAND, ARG_CONFIG, ARG_HOST, ARG_NAME, ARG_PATH, ARG_PID, ARG_PORT, ARG_READONLY ); System.out.println( padArg( ARG_HOST, longestArgLength ) + "Domain name or IP of host to connect to (default: localhost)" + "\n" + padArg( ARG_PORT, longestArgLength ) + "Port of host to connect to (default: " + SimpleAppServer.DEFAULT_PORT + ")\n" + padArg( ARG_NAME, longestArgLength ) + "RMI name, i.e. rmi://<host>:<port>/<name> (default: " + SimpleAppServer.DEFAULT_NAME + ")\n" + padArg( ARG_PID, longestArgLength ) + "Process ID to connect to\n" + padArg( ARG_COMMAND, longestArgLength ) + "Command line to execute. After executing it the " + "shell exits\n" + padArg( ARG_FILE, longestArgLength ) + "File containing commands to execute, or '-' to read " + "from stdin. After executing it the shell exits\n" + padArg( ARG_READONLY, longestArgLength ) + "Connect in readonly mode (only for connecting " + "with -" + ARG_PATH + ")\n" + padArg( ARG_PATH, longestArgLength ) + "Points to a neo4j db path so that a local server can " + "be started there\n" + padArg( ARG_CONFIG, longestArgLength ) + "Points to a config file when starting a local " + "server\n\n" + "Example arguments for remote:\n" + "\t-" + ARG_PORT + " " + port + "\n" + "\t-" + ARG_HOST + " " + "192.168.1.234" + " -" + ARG_PORT + " " + port + " -" + ARG_NAME + "" + " " + name + "\n" + "\t-" + ARG_HOST + " " + "localhost" + " -" + ARG_READONLY + "\n" + "\t...or no arguments for default values\n" + "Example arguments for local:\n" + "\t-" + ARG_PATH + " /path/to/db" + "\n" + "\t-" + ARG_PATH + " /path/to/db -" + ARG_CONFIG + " /path/to/neo4j.config" + "\n" + "\t-" + ARG_PATH + " /path/to/db -" + ARG_READONLY ); } private static String padArg( String arg, int length ) { return " -" + pad( arg, length ) + " "; } private static String pad( String string, int length ) { // Rather inefficient while ( string.length() < length ) { string = string + " "; } return string; } }
false
community_shell_src_main_java_org_neo4j_shell_StartClient.java
1,557
public class SilentLocalOutput implements Output { @Override public Appendable append( CharSequence csq ) throws IOException { return this; } @Override public Appendable append( CharSequence csq, int start, int end ) throws IOException { return this; } @Override public Appendable append( char c ) throws IOException { return this; } @Override public void print( Serializable object ) throws RemoteException { } @Override public void println() throws RemoteException { } @Override public void println( Serializable object ) throws RemoteException { } }
false
community_shell_src_test_java_org_neo4j_shell_SilentLocalOutput.java
1,558
@Description( "Settings for the remote shell extension" ) public class ShellSettings { @Description("Enable a remote shell server which shell clients can log in to") public static final Setting<Boolean> remote_shell_enabled = setting( "remote_shell_enabled", BOOLEAN, FALSE ); public static final Setting<String> remote_shell_host = setting( "remote_shell_host", STRING, "localhost", illegalValueMessage( "must be a valid name", matches( ANY ) ) ); public static final Setting<Integer> remote_shell_port = setting( "remote_shell_port", INTEGER, "1337", port ); public static final Setting<Boolean> remote_shell_read_only = setting( "remote_shell_read_only", BOOLEAN, FALSE ); public static final Setting<String> remote_shell_name = setting( "remote_shell_name", STRING, "shell", illegalValueMessage( "must be a valid name", matches( ANY ) ) ); }
false
community_shell_src_main_java_org_neo4j_shell_ShellSettings.java
1,559
public abstract class ShellLobby { public static final Map<String, Serializable> NO_INITIAL_SESSION = Collections.unmodifiableMap( Collections.<String,Serializable>emptyMap() ); /** * To get rid of the RemoteException, uses a constructor without arguments. * @param cls the class of the server to instantiate. * @throws ShellException if the object couldn't be instantiated. * @return a new shell server. */ public static ShellServer newServer( Class<? extends ShellServer> cls ) throws ShellException { try { return cls.newInstance(); } catch ( Exception e ) { throw new RuntimeException( e ); } } /** * Creates a client and "starts" it, i.e. grabs the console prompt. * @param server the server (in the same JVM) which the client will * communicate with. * @return the new shell client. */ public static ShellClient newClient( ShellServer server ) throws ShellException { return newClient( server, new HashMap<String, Serializable>() ); } /** * Creates a client and "starts" it, i.e. grabs the console prompt. * @param server the server (in the same JVM) which the client will * communicate with. * @param initialSession the initial session variables the shell will have, * in addition to those provided by the server initially. * @return the new shell client. */ public static ShellClient newClient( ShellServer server, Map<String, Serializable> initialSession ) throws ShellException { return new SameJvmClient( initialSession, server ); } /** * Creates a client and "starts" it, i.e. grabs the console prompt. * It will try to find a remote server on "localhost". * @param port the RMI port. * @param name the RMI name. * @throws ShellException if no server was found at the RMI location. * @return the new shell client. */ public static ShellClient newClient( int port, String name ) throws ShellException { return newClient( "localhost", port, name ); } /** * Creates a client and "starts" it, i.e. grabs the console prompt. * It will try to find a remote server on "localhost" and default RMI name. * @param port the RMI port. * @throws ShellException if no server was found at the RMI location. * @return the new shell client. */ public static ShellClient newClient( int port ) throws ShellException { return newClient( "localhost", port ); } /** * Creates a client and "starts" it, i.e. grabs the console prompt. * It will try to find a remote server to connect to. * @param host the host (IP or domain name). * @param port the RMI port. * @param name the RMI name. * @throws ShellException if no server was found at the RMI location. * @return the new shell client. */ public static ShellClient newClient( String host, int port, String name ) throws ShellException { return newClient( RmiLocation.location( host, port, name ) ); } /** * Creates a client and "starts" it, i.e. grabs the console prompt. * It will try to find a remote server to connect to. Uses default RMI name. * @param host the host (IP or domain name). * @param port the RMI port. * @throws ShellException if no server was found at the RMI location. * @return the new shell client. */ public static ShellClient newClient( String host, int port ) throws ShellException { return newClient( host, port, SimpleAppServer.DEFAULT_NAME ); } /** * Creates a client and "starts" it, i.e. grabs the console prompt. * It will try to find a remote server specified by {@code serverLocation}. * @param serverLocation the RMI location of the server to connect to. * @throws ShellException if no server was found at the RMI location. * @return the new shell client. */ public static ShellClient newClient( RmiLocation serverLocation ) throws ShellException { return newClient( serverLocation, new HashMap<String, Serializable>() ); } /** * Creates a client and "starts" it, i.e. grabs the console prompt. * It will try to find a remote server specified by {@code serverLocation}. * @param serverLocation the RMI location of the server to connect to. * @param initialSession the initial session variables the shell will have, * in addition to those provided by the server initially. * @throws ShellException if no server was found at the RMI location. * @return the new shell client. */ public static ShellClient newClient( RmiLocation serverLocation, Map<String, Serializable> initialSession ) throws ShellException { return new RemoteClient( initialSession, serverLocation ); } /** * Creates a client and "starts" it, i.e. grabs the console prompt. * It will try to find a remote server on {@code host} with default * port and name. * @param host host to connect to. * @throws ShellException if no server was found at the RMI location. * @return the new shell client. */ public static ShellClient newClient( String host ) throws ShellException { return newClient( host, SimpleAppServer.DEFAULT_PORT, SimpleAppServer.DEFAULT_NAME ); } /** * Creates a client and "starts" it, i.e. grabs the console prompt. * It will try to find a remote server on localhost with default * port and name. * @throws ShellException if no server was found at the RMI location. * @return the new shell client. */ public static ShellClient newClient() throws ShellException { return newClient( "localhost", SimpleAppServer.DEFAULT_PORT, SimpleAppServer.DEFAULT_NAME ); } public static RmiLocation remoteLocation() { return remoteLocation( SimpleAppServer.DEFAULT_PORT ); } public static RmiLocation remoteLocation( int port ) { return remoteLocation( port, SimpleAppServer.DEFAULT_NAME ); } public static RmiLocation remoteLocation( int port, String rmiName ) { return RmiLocation.location( "localhost", port, rmiName ); } }
false
community_shell_src_main_java_org_neo4j_shell_ShellLobby.java
1,560
public class ShellException extends Exception { private static final long serialVersionUID = 1L; private final String stackTraceAsString; public ShellException( String message ) { this( message, (String) null ); } private ShellException( String message, Throwable cause ) { super( message, cause ); this.stackTraceAsString = null; } private ShellException( String message, String stackTraceAsString ) { super( message ); this.stackTraceAsString = stackTraceAsString; } @Override public void printStackTrace( PrintStream s ) { if ( stackTraceAsString != null ) { s.print( stackTraceAsString ); } else if ( getCause() != null ) { getCause().printStackTrace( s ); } else { super.printStackTrace( s ); } } @Override public void printStackTrace( PrintWriter s ) { if ( stackTraceAsString != null ) { s.print( stackTraceAsString ); } else if ( getCause() != null ) { getCause().printStackTrace( s ); } else { super.printStackTrace( s ); } } /** * Serializes a {@link Throwable} to a String and uses that as a message * in a {@link ShellException}. This is because we can't rely on the * client having the full classpath the server has. * @param cause the {@link Throwable} to wrap in a {@link ShellException}. * @return the {@link ShellException} wrapped around the {@code cause}. */ public static ShellException wrapCause( Throwable cause ) { if ( isCompletelyRecognizedException( cause ) ) { return cause instanceof ShellException ? (ShellException) cause : new ShellException( getFirstMessage( cause ), cause ); } else { return softWrap( cause ); } } private static ShellException softWrap( Throwable cause ) { String stackTraceAsString = stackTraceAsString( cause ); String message = getFirstMessage( cause ); if ( !( cause instanceof ShellException ) ) { message = cause.getClass().getSimpleName() + ": " + message; } return new ShellException( message, stackTraceAsString ); } public static String getFirstMessage( Throwable cause ) { while ( cause != null ) { String message = cause.getMessage(); if ( message != null && message.length() > 0 ) { return message; } cause = cause.getCause(); } return null; } private static boolean isCompletelyRecognizedException( Throwable e ) { String packageName = e.getClass().getPackage().getName(); if ( !( e instanceof ShellException ) && !packageName.startsWith( "java." ) ) { return false; } Throwable cause = e.getCause(); return cause == null ? true : isCompletelyRecognizedException( cause ); } public static String stackTraceAsString( Throwable cause ) { StringWriter writer = new StringWriter(); PrintWriter printWriter = new PrintWriter( writer, false ); cause.printStackTrace( printWriter ); printWriter.close(); return writer.getBuffer().toString(); } public String getStackTraceAsString() { return stackTraceAsString; } }
false
community_shell_src_main_java_org_neo4j_shell_ShellException.java
1,561
public class ShellDocTest { private final static String NL = System.getProperty( "line.separator" ); private AppCommandParser parse( final String line ) throws Exception { return new AppCommandParser( new GraphDatabaseShellServer( null ), line ); } @Test public void testParserEasy() throws Exception { AppCommandParser parser = parse( "ls -la" ); assertEquals( "ls", parser.getAppName() ); assertEquals( 2, parser.options().size() ); assertTrue( parser.options().containsKey( "l" ) ); assertTrue( parser.options().containsKey( "a" ) ); assertTrue( parser.arguments().isEmpty() ); } @Test public void parsingUnrecognizedOptionShouldFail() throws Exception { String unrecognizedOption = "unrecognized-option"; try { parse( "ls --" + unrecognizedOption ); fail( "Should fail when encountering unrecognized option" ); } catch ( ShellException e ) { assertThat( e.getMessage(), containsString( unrecognizedOption ) ); } } @Test public void testParserArguments() throws Exception { AppCommandParser parser = parse( "set -t java.lang.Integer key value" ); assertEquals( "set", parser.getAppName() ); assertTrue( parser.options().containsKey( "t" ) ); assertEquals( "java.lang.Integer", parser.options().get( "t" ) ); assertEquals( 2, parser.arguments().size() ); assertEquals( "key", parser.arguments().get( 0 ) ); assertEquals( "value", parser.arguments().get( 1 ) ); assertShellException( "set -tsd" ); } @Test public void testEnableRemoteShellOnCustomPort() throws Exception { int port = 8085; GraphDatabaseService graphDb = new TestGraphDatabaseFactory(). newImpermanentDatabaseBuilder(). setConfig( ShellSettings.remote_shell_enabled, "true" ). setConfig( ShellSettings.remote_shell_port, "" + port ). newGraphDatabase(); RemoteClient client = new RemoteClient( NO_INITIAL_SESSION, remoteLocation( port ), new CollectingOutput() ); client.evaluate( "help" ); client.shutdown(); graphDb.shutdown(); } @Test public void testEnableServerOnDefaultPort() throws Exception { GraphDatabaseService graphDb = new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder(). setConfig( ShellSettings.remote_shell_enabled, Settings.TRUE ). newGraphDatabase(); try { RemoteClient client = new RemoteClient( NO_INITIAL_SESSION, remoteLocation(), new CollectingOutput() ); client.evaluate( "help" ); client.shutdown(); } finally { graphDb.shutdown(); } } @Test public void testRemoveReferenceNode() throws Exception { GraphDatabaseAPI db = (GraphDatabaseAPI)new TestGraphDatabaseFactory().newImpermanentDatabase(); final GraphDatabaseShellServer server = new GraphDatabaseShellServer( db, false ); Documenter doc = new Documenter( "sample session", server ); doc.add( "mknode --cd", "", "Create a node"); doc.add( "pwd", "", "where are we?" ); doc.add( "set name \"Jon\"", "", "On the current node, set the key \"name\" to value \"Jon\"" ); doc.add( "start n=node(0) return n;", "Jon", "send a cypher query" ); doc.add( "mkrel -c -d i -t LIKES --np \"{'app':'foobar'}\"", "", "make an incoming relationship of type " + "LIKES, create the end node with the node properties specified." ); doc.add( "ls", "1", "where are we?" ); doc.add( "cd 1", "", "change to the newly created node" ); doc.add( "ls -avr", "LIKES", "list relationships, including relationship id" ); doc.add( "mkrel -c -d i -t KNOWS --np \"{'name':'Bob'}\"", "", "create one more KNOWS relationship and the " + "end node" ); doc.add( "pwd", "0", "print current history stack" ); doc.add( "ls -avr", "KNOWS", "verbose list relationships" ); db.beginTx(); doc.run(); doc.add( "rmnode -f 0", "", "delete node 0" ); doc.add( "cd 0", "", "cd back to node 0" ); doc.add( "pwd", "(?)", "the node doesn't exist now" ); doc.add( "mknode --cd --np \"{'name':'Neo'}\"", "", "create a new node and go to it" ); server.shutdown(); db.shutdown(); } @Test public void testDumpCypherResultSimple() throws Exception { GraphDatabaseAPI db = (GraphDatabaseAPI)new TestGraphDatabaseFactory().newImpermanentDatabase(); final GraphDatabaseShellServer server = new GraphDatabaseShellServer( db, false ); try ( Transaction tx = db.beginTx() ) { Documenter doc = new Documenter( "simple cypher result dump", server ); doc.add( "mknode --cd --np \"{'name':'Neo'}\"", "", "create a new node and go to it" ); doc.add( "mkrel -c -d i -t LIKES --np \"{'app':'foobar'}\"", "", "create a relationship" ); doc.add( "dump START n=node({self}) MATCH (n)-[r]-(m) return n,r,m;", "create (_0 {`name`:\"Neo\"})", "Export the cypher statement results" ); doc.run(); } server.shutdown(); db.shutdown(); } @Test public void testDumpDatabase() throws Exception { GraphDatabaseAPI db = (GraphDatabaseAPI)new TestGraphDatabaseFactory().newImpermanentDatabase(); final GraphDatabaseShellServer server = new GraphDatabaseShellServer( db, false ); Documenter doc = new Documenter( "database dump", server ); doc.add( "create index on :Person(name);", "", "create an index" ); doc.add( "create (m:Person:Hacker {name:'Mattias'}), (m)-[:KNOWS]->(m);", "", "create one labeled node and a relationship" ); doc.add( "dump", "begin" + NL +"create index on :`Person`(`name`)" + NL +"create (_0:`Person`:`Hacker` {`name`:\"Mattias\"})" + NL +"create _0-[:`KNOWS`]->_0" + NL +";" + NL +"commit", "Export the whole database including indexes" ); doc.run(); server.shutdown(); db.shutdown(); } @Test public void testMatrix() throws Exception { GraphDatabaseAPI db = (GraphDatabaseAPI) new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder() .loadPropertiesFromURL( getClass().getResource( "/autoindex.properties" ) ).newGraphDatabase(); final GraphDatabaseShellServer server = new GraphDatabaseShellServer( db, false ); Documenter doc = new Documenter( "a matrix example", server ); doc.add("mknode --cd", "", "Create a reference node"); doc.add( "mkrel -t ROOT -c -v", "created", "create the Thomas Andersson node" ); doc.add( "cd 1", "", "go to the new node" ); doc.add( "set name \"Thomas Andersson\"", "", "set the name property" ); doc.add( "mkrel -t KNOWS -cv", "", "create Thomas direct friends" ); doc.add( "cd 2", "", "go to the new node" ); doc.add( "set name \"Trinity\"", "", "set the name property" ); doc.add( "cd ..", "", "go back in the history stack" ); doc.add( "mkrel -t KNOWS -cv", "", "create Thomas direct friends" ); doc.add( "cd 3", "", "go to the new node" ); doc.add( "set name \"Morpheus\"", "", "set the name property" ); doc.add( "mkrel -t KNOWS 2", "", "create relationship to Trinity" ); doc.add( "ls -rv", "", "list the relationships of node 3" ); doc.add( "cd -r 2", "", "change the current position to relationship #2" ); doc.add( "set -t int age 3", "", "set the age property on the relationship" ); doc.add( "cd ..", "", "back to Morpheus" ); doc.add( "cd -r 3", "", "next relationship" ); doc.add( "set -t int age 90", "", "set the age property on the relationship" ); doc.add( "cd start", "", "position to the start node of the current relationship" ); doc.add( "", "", "We're now standing on Morpheus node, so let's create the rest of the friends." ); doc.add( "mkrel -t KNOWS -c", "", "new node" ); doc.add( "ls -r", "", "list relationships on the current node" ); doc.add( "cd 4", "", "go to Cypher" ); doc.add( "set name Cypher", "", "set the name" ); doc.add( "mkrel -ct KNOWS", "", "create new node from Cypher" ); //TODO: how to list outgoing relationships? //doc.add( "ls -rd out", "", "list relationships" ); doc.add( "ls -r", "", "list relationships" ); doc.add( "cd 5", "", "go to the Agent Smith node" ); doc.add( "set name \"Agent Smith\"", "", "set the name" ); doc.add( "mkrel -cvt CODED_BY", "", "outgoing relationship and new node" ); doc.add( "cd 6", "", "go there" ); doc.add( "set name \"The Architect\"", "", "set the name" ); doc.add( "cd", "", "go to the first node in the history stack" ); doc.add( "", "", "" ); doc.add( "start morpheus = node:node_auto_index(name='Morpheus') " + "match morpheus-[:KNOWS]-zionist " + "return zionist.name;", "Trinity", "Morpheus' friends, looking up Morpheus by name in the Neo4j autoindex" ); doc.add( "cypher 2.0 start morpheus = node:node_auto_index(name='Morpheus') " + "match morpheus-[:KNOWS]-zionist " + "return zionist.name;", "Cypher", "Morpheus' friends, looking up Morpheus by name in the Neo4j autoindex" ); // doc.add( "profile start morpheus = node:node_auto_index(name='Morpheus') " + // "match morpheus-[:KNOWS]-zionist " + // "return zionist.name;", // "ColumnFilter", // "profile the query by displaying more query execution information" ); doc.run(); // wrapping this in a tx will cause problems, so we don't server.shutdown(); try (Transaction tx = db.beginTx()) { assertEquals( 7, Iterables.count( GlobalGraphOperations.at( db ).getAllRelationships() ) ); assertEquals( 7, Iterables.count( GlobalGraphOperations.at( db ).getAllNodes() ) ); boolean foundRootAndNeoRelationship = false; for ( Relationship relationship : GlobalGraphOperations.at( db ) .getAllRelationships() ) { if ( relationship.getType().name().equals( "ROOT" ) ) { foundRootAndNeoRelationship = true; assertFalse( "The root node should not have a name property.", relationship.getStartNode() .hasProperty( "name" ) ); assertEquals( "Thomas Andersson", relationship.getEndNode() .getProperty( "name", null ) ); } } assertTrue( "Could not find the node connecting the root and Neo nodes.", foundRootAndNeoRelationship ); tx.success(); } try ( PrintWriter writer = doc.getWriter( "shell-matrix-example-graph" ); Transaction tx = db.beginTx() ) { writer.println( createGraphViz( "Shell Matrix Example", db, "graph" ) ); writer.flush(); tx.success(); } db.shutdown(); } private void assertShellException( final String command ) throws Exception { try { this.parse( command ); fail( "Should fail with " + ShellException.class.getSimpleName() ); } catch ( ShellException e ) { // Good } } }
false
community_shell_src_test_java_org_neo4j_shell_ShellDocTest.java
1,562
public class SessionTest { private Session session; @Before public void setUp() throws Exception { session = new Session( 1 ); } @Test(expected = ShellException.class) public void cannotSetInvalidVariableName() throws ShellException { session.set( "foo bar", 42 ); } @Test public void canSetVariableName() throws ShellException { session.set( "_foobar", 42 ); } @Test(expected = ShellException.class) public void cannotGetInvalidVariableName() throws ShellException { session.get( "foo bar" ); } @Test public void canGetVariableName() throws ShellException { session.set( "_foobar", 42); assertEquals( 42, session.get( "_foobar" )); } @Test(expected = ShellException.class) public void cannotRemoveInvalidVariableName() throws ShellException { session.remove( "foo bar" ); } @Test public void canRemoveVariableName() throws ShellException { session.set( "_foobar", 42); assertEquals( 42, session.remove( "_foobar" )); } @Test public void canCheckInvalidVariableName() throws ShellException { assertEquals( false, session.has( "foo bar" )); } @Test public void canCheckVariableName() throws ShellException { assertEquals( false, session.has( "_foobar" )); session.set( "_foobar", 42 ); assertEquals( true, session.has( "_foobar" )); } }
false
community_shell_src_test_java_org_neo4j_shell_SessionTest.java
1,563
public class Session { private final Serializable id; private final Map<String, Object> properties = new HashMap<String, Object>(); private final Map<String, String> aliases = new HashMap<String, String>(); public Session( Serializable id ) { this.id = id; } public Serializable getId() { return id; } /** * Sets a session value. * @param key the session key. * @param value the value. */ public void set( String key, Object value ) throws ShellException { Variables.checkIsValidVariableName( key ); setInternal( key, value ); } private void setInternal( String key, Object value ) { properties.put( key, value ); } /** * @param key the key to get the session value for. * @return the value for the {@code key} or {@code null} if not found. */ public Object get( String key ) throws ShellException { Variables.checkIsValidVariableName( key ); return getInternal( key ); } private Object getInternal( String key ) { return properties.get( key ); } /** * @param key the key to check the session value for. * @return true if the session contains a variable with that name. */ public boolean has( String key ) { return properties.containsKey( key ); } /** * Removes a value from the session. * @param key the session key to remove. * @return the removed value, or {@code null} if none. */ public Object remove( String key ) throws ShellException { Variables.checkIsValidVariableName( key ); return properties.remove( key ); } /** * @return all the available session keys. */ public String[] keys() { return properties.keySet().toArray( new String[ properties.size() ] ); } /** * Returns the session as a {@link Map} representation. Changes in the * returned instance won't be reflected in the session. * @return the session as a {@link Map}. */ public Map<String, Object> asMap() { return properties; } public void removeAlias( String key ) { aliases.remove( key ); } public void setAlias( String key, String value ) { aliases.put( key, value ); } public Set<String> getAliasKeys() { return aliases.keySet(); } public String getAlias( String key ) { return aliases.get( key ); } public void setPath( String path ) { setInternal( Variables.WORKING_DIR_KEY, path ); } public String getPath( ) { return (String) getInternal( Variables.WORKING_DIR_KEY ); } public void setCurrent( final String value ) { setInternal( Variables.CURRENT_KEY, value ); } public String getCurrent() { return ( String ) getInternal( Variables.CURRENT_KEY ); } public Integer getCommitCount() { return (Integer) getInternal( Variables.TX_COUNT ); } public void setCommitCount( int commitCount ) { setInternal( Variables.TX_COUNT, commitCount ); } public String getTitleKeys() throws ShellException { return ( String ) get( Variables.TITLE_KEYS_KEY ); } public String getMaxTitleLength() throws ShellException { return ( String ) get( Variables.TITLE_MAX_LENGTH ); } }
false
community_shell_src_main_java_org_neo4j_shell_Session.java
1,564
public class ServerClientInteractionTest { private GraphDatabaseAPI db; @Test public void shouldConsiderAndInterpretCustomClientPrompt() throws Exception { // GIVEN client.setSessionVariable( PROMPT_KEY, "MyPrompt \\d \\t$ " ); // WHEN Response response = server.interpretLine( client.getId(), "", out ); // THEN String regexPattern = "MyPrompt .{1,3} .{1,3} \\d{1,2} \\d{2}:\\d{2}:\\d{2}\\$"; assertTrue( "Prompt from server '" + response.getPrompt() + "' didn't match pattern '" + regexPattern + "'", compile( regexPattern ).matcher( response.getPrompt() ).find() ); } private SimpleAppServer server; private ShellClient client; private SilentLocalOutput out; @Before public void before() throws Exception { db = new ImpermanentGraphDatabase( ); server = new GraphDatabaseShellServer( db ); out = new SilentLocalOutput(); client = new SameJvmClient( MapUtil.<String,Serializable>genericMap(), server, out ); } @After public void after() throws Exception { server.shutdown(); db.shutdown(); } }
false
community_shell_src_test_java_org_neo4j_shell_ServerClientInteractionTest.java
1,565
public class Response implements Serializable { private final String prompt; private final Continuation continuation; public Response( String prompt, Continuation continuation ) { this.prompt = prompt; this.continuation = continuation; } public String getPrompt() { return prompt; } public Continuation getContinuation() { return continuation; } }
false
community_shell_src_main_java_org_neo4j_shell_Response.java
1,566
public class OutputAsWriterTest { private PrintStream out; private ByteArrayOutputStream buffer; private SystemOutput output; private OutputAsWriter writer; @Before public void setUp() throws Exception { out = System.out; buffer = new ByteArrayOutputStream(); System.setOut( new PrintStream( buffer ) ); output = new SystemOutput(); writer = new OutputAsWriter( output ); } @After public void tearDown() throws Exception { System.setOut( out ); } @Test public void shouldNotFlushWithoutNewline() throws Exception { writer.write( "foo".toCharArray() ); assertEquals( 0, buffer.size() ); } @Test public void shouldFlushWithNewline() throws Exception { String s = format( "foobar%n" ); writer.write( s.toCharArray() ); assertEquals( s.length(), buffer.size() ); assertEquals( s, buffer.toString() ); } @Test public void shouldFlushPartiallyWithNewlineInMiddle() throws Exception { String firstPart = format( "foo%n" ); String secondPart = "bar"; String string = firstPart + secondPart; String newLine = format( "%n" ); String fullString = string + newLine; writer.write( string.toCharArray() ); assertEquals( firstPart.length(), buffer.size() ); assertEquals( firstPart, buffer.toString() ); writer.write( newLine.toCharArray() ); assertEquals( fullString.length(), buffer.size() ); assertEquals( fullString, buffer.toString() ); } }
false
community_shell_src_test_java_org_neo4j_shell_OutputAsWriterTest.java
1,567
public class OutputAsWriter extends Writer { private final static String LINE_SEPARATOR = System.getProperty( "line.separator" ); private final Output out; public OutputAsWriter( Output out ) { this.out = out; } @Override public void write( char[] cbuf, int off, int len ) throws IOException { String string = String.valueOf( cbuf, off, len ); int lastNewline = string.lastIndexOf( LINE_SEPARATOR ); if ( lastNewline == -1 ) { out.print( string ); } else { out.println( string.substring( 0, lastNewline ) ); out.print( string.substring( lastNewline + LINE_SEPARATOR.length() ) ); } } @Override public void flush() throws IOException { } @Override public void close() throws IOException { } }
false
community_shell_src_main_java_org_neo4j_shell_OutputAsWriter.java
1,568
public class OptionDefinition { private OptionValueType type; private String description; /** * @param type the type for the option. * @param description the description of the option. */ public OptionDefinition( OptionValueType type, String description ) { this.type = type; this.description = description; } /** * @return the option value type. */ public OptionValueType getType() { return this.type; } /** * @return the description. */ public String getDescription() { return this.description; } }
false
community_shell_src_main_java_org_neo4j_shell_OptionDefinition.java
1,569
public class TestClientReconnect extends AbstractShellTest { @Test public void remoteClientAbleToReconnectAndContinue() throws Exception { makeServerRemotelyAvailable(); ShellClient client = newRemoteClient(); executeCommand( client, "help", "Available commands" ); restartServer(); makeServerRemotelyAvailable(); executeCommand( client, "help", "Available commands" ); client.shutdown(); } @Test public void initialSessionValuesSurvivesReconnect() throws Exception { createRelationshipChain( 2 ); makeServerRemotelyAvailable(); Map<String, Serializable> initialSession = MapUtil.<String, Serializable>genericMap( "TITLE_KEYS", "test" ); ShellClient client = newRemoteClient( initialSession ); String name = "MyTest"; client.evaluate( "mknode --cd" ); client.evaluate( "set test " + name ); assertTrue( client.getPrompt().contains( name ) ); client.shutdown(); } }
false
community_shell_src_test_java_org_neo4j_shell_TestClientReconnect.java
1,570
public class TestReadOnlyServer extends AbstractShellTest { @Override protected ShellServer newServer( GraphDatabaseAPI db ) throws ShellException, RemoteException { return new GraphDatabaseShellServer( new ReadOnlyGraphDatabaseProxy( db ) ); } @Test public void executeReadCommands() throws Exception { Relationship[] rels = createRelationshipChain( 3 ); executeCommand( "cd " + getStartNodeId(rels[0]) ); executeCommand( "ls" ); executeCommand( "cd " + getEndNodeId(rels[0]) ); executeCommand( "ls", "<", ">" ); executeCommand( "trav", "me" ); } @Test public void readOnlyTransactionsShouldNotFail() throws Exception { Relationship[] rels = createRelationshipChain( 3 ); executeCommand( "begin" ); executeCommand( "cd " + getStartNodeId(rels[0]) ); executeCommand( "ls" ); executeCommand( "commit" ); } private long getEndNodeId( Relationship rel ) { try ( Transaction ignore = db.beginTx() ) { return rel.getEndNode().getId(); } } private long getStartNodeId( Relationship rel ) { try ( Transaction ignore = db.beginTx() ) { return rel.getStartNode().getId(); } } @Test public void executeWriteCommands() throws Exception { executeCommandExpectingException( "mknode", "read only" ); } }
false
community_shell_src_test_java_org_neo4j_shell_TestReadOnlyServer.java
1,571
public class JshExecutor extends ScriptExecutor { static { String jythonSystemVariableName = "python.home"; if ( System.getProperty( jythonSystemVariableName ) == null ) { String variable = tryFindEnvironmentVariable( "JYTHON_HOME", "JYTHONHOME", "JYTHON", "PYTHON_HOME", "PYTHONHOME", "PYTHON" ); variable = variable == null ? "/usr/local/jython" : variable; System.setProperty( jythonSystemVariableName, variable ); } } private static String tryFindEnvironmentVariable( String... examples ) { Map<String, String> env = System.getenv(); for ( String example : examples ) { for ( String envKey : env.keySet() ) { if ( envKey.contains( example ) ) { return env.get( envKey ); } } } return null; } /** * The class name which represents the PythonInterpreter class. */ private static final String INTERPRETER_CLASS = "org.python.util.PythonInterpreter"; @Override protected void ensureDependenciesAreInClasspath() throws ShellException { try { Class.forName( INTERPRETER_CLASS ); } catch ( ClassNotFoundException e ) { throw new ShellException( "Jython not found in the classpath" ); } } @Override protected String getPathKey() { return "JSH_PATH"; } @Override protected Object newInterpreter( String[] paths ) throws ShellException { try { return Class.forName( INTERPRETER_CLASS ).newInstance(); } catch ( Exception e ) { throw new ShellException( "Invalid jython classes" ); } } @Override protected void runScript( Object interpreter, String scriptName, Map<String, Object> properties, String[] paths ) throws Exception { File scriptFile = findScriptFile( scriptName, paths ); Output out = ( Output ) properties.remove( "out" ); interpreter.getClass().getMethod( "setOut", Writer.class ).invoke( interpreter, new OutputWriter( out ) ); Method setMethod = interpreter.getClass().getMethod( "set", String.class, Object.class ); for ( String key : properties.keySet() ) { setMethod.invoke( interpreter, key, properties.get( key ) ); } interpreter.getClass().getMethod( "execfile", String.class ) .invoke( interpreter, scriptFile.getAbsolutePath() ); } private File findScriptFile( String scriptName, String[] paths ) throws ShellException { for ( String path : paths ) { File result = findScriptFile( scriptName, path ); if ( result != null ) { return result; } } throw new ShellException( "No script '" + scriptName + "' found" ); } private File findScriptFile( String scriptName, String path ) { File pathFile = new File( path ); if ( !pathFile.exists() ) { return null; } for ( File file : pathFile.listFiles() ) { String name = file.getName(); int dotIndex = name.lastIndexOf( '.' ); name = dotIndex == -1 ? name : name.substring( 0, dotIndex ); String extension = dotIndex == -1 ? null : file.getName().substring( dotIndex + 1 ); if ( scriptName.equals( name ) && ( extension == null || extension.toLowerCase().equals( "py" ) ) ) { return file; } } return null; } private static class OutputWriter extends Writer { private Output out; OutputWriter( Output out ) { this.out = out; } @Override public Writer append( char c ) throws IOException { out.append( c ); return this; } @Override public Writer append( CharSequence csq, int start, int end ) throws IOException { out.append( csq, start, end ); return this; } @Override public Writer append( CharSequence csq ) throws IOException { out.append( csq ); return this; } @Override public void close() throws IOException { } @Override public void flush() throws IOException { } @Override public void write( char[] cbuf, int off, int len ) throws IOException { out.print( new String( cbuf, off, len ) ); } @Override public void write( char[] cbuf ) throws IOException { out.print( new String( cbuf ) ); } @Override public void write( int c ) throws IOException { out.print( String.valueOf( c ) ); } @Override public void write( String str, int off, int len ) throws IOException { char[] cbuf = new char[ len ]; str.getChars( off, off + len, cbuf, 0 ); write( cbuf, off, len ); } @Override public void write( String str ) throws IOException { out.print( str ); } } }
false
community_shell_src_main_java_org_neo4j_shell_apps_extra_JshExecutor.java
1,572
public class TestRmiPublication { @Test public void jvmShouldDieEvenIfWeLeaveSamveJvmClientIsLeftHanging() throws Exception { assertEquals( 0, spawnJvm( DontShutdownClient.class, "client" ) ); } @Test public void jvmShouldDieEvenIfLocalServerIsLeftHanging() throws Exception { assertEquals( 0, spawnJvm( DontShutdownLocalServer.class, "server" ) ); } private int spawnJvm( Class<?> mainClass, String name ) throws Exception { String dir = forTest( getClass() ).cleanDirectory( name ).getAbsolutePath(); return waitForExit( getRuntime().exec( new String[] { "java", "-cp", getProperty( "java.class.path" ), mainClass.getName(), dir } ), 20 ); } private int waitForExit( Process process, int maxSeconds ) throws InterruptedException { try { long endTime = System.currentTimeMillis() + maxSeconds*1000; ProcessStreamHandler streamHandler = new ProcessStreamHandler( process, false ); streamHandler.launch(); try { while ( System.currentTimeMillis() < endTime ) { try { return process.exitValue(); } catch ( IllegalThreadStateException e ) { // OK, not exited yet Thread.sleep( 100 ); } } tempHackToGetThreadDump(process); throw new RuntimeException( "Process didn't exit on its own." ); } finally { streamHandler.cancel(); } } finally { process.destroy(); } } private void tempHackToGetThreadDump( Process process ) { try { Field pidField = process.getClass().getDeclaredField( "pid" ); pidField.setAccessible( true ); int pid = (int)pidField.get( process ); ProcessBuilder processBuilder = new ProcessBuilder( "/bin/sh", "-c", "kill -3 " + pid ); processBuilder.redirectErrorStream( true ); Process dumpProc = processBuilder.start(); ProcessStreamHandler streamHandler = new ProcessStreamHandler(dumpProc, false); streamHandler.launch(); try { process.waitFor(); } finally { streamHandler.cancel(); } } catch( Throwable e ) { e.printStackTrace(); } } }
false
community_shell_src_test_java_org_neo4j_shell_TestRmiPublication.java
1,573
public class Jsh extends AbstractApp { public Continuation execute( AppCommandParser parser, Session session, Output out ) throws Exception { String line = parser.getLineWithoutApp(); new JshExecutor().execute( line, session, out ); return Continuation.INPUT_COMPLETE; } @Override public String getDescription() { JshExecutor anExecutor = new JshExecutor(); return "Runs python (jython) scripts. Usage: jsh <python script line>\n" + "Example: jsh --doSomething arg1 \"arg 2\" " + "--doSomethingElse arg1\n\n" + "Python scripts doSomething.py and doSomethingElse.py " + "must exist\n" + "in one of environment variable " + anExecutor.getPathKey() + " paths (default is " + anExecutor.getDefaultPaths() + ")"; } }
false
community_shell_src_main_java_org_neo4j_shell_apps_extra_Jsh.java
1,574
public static class GshOutput implements Output { private Output source; GshOutput( Output output ) { this.source = output; } public void print( Serializable object ) throws RemoteException { source.print( object ); } public void println( Serializable object ) throws RemoteException { source.println( object ); } public Appendable append( char c ) throws IOException { return source.append( c ); } public Appendable append( CharSequence csq, int start, int end ) throws IOException { return source.append( csq, start, end ); } public Appendable append( CharSequence csq ) throws IOException { return source.append( csq ); } /** * Prints an object to the wrapped {@link Output}. * @param object the object to print. * @throws RemoteException RMI error. */ public void print( Object object ) throws RemoteException { source.print( object.toString() ); } public void println() throws RemoteException { source.println(); } /** * Prints an object to the wrapped {@link Output}. * @param object the object to print. * @throws RemoteException RMI error. */ public void println( Object object ) throws RemoteException { source.println( object.toString() ); } }
false
community_shell_src_main_java_org_neo4j_shell_apps_extra_GshExecutor.java
1,575
public class GshExecutor extends ScriptExecutor { private static final String BINDING_CLASS = "groovy.lang.Binding"; private static final String ENGINE_CLASS = "groovy.util.GroovyScriptEngine"; @Override protected String getDefaultPaths() { return super.getDefaultPaths() + ":" + "src" + File.separator + "main" + File.separator + "groovy"; } @Override protected String getPathKey() { return "GSH_PATH"; } @Override protected void runScript( Object groovyScriptEngine, String scriptName, Map<String, Object> properties, String[] paths ) throws Exception { properties.put( "out", new GshOutput( ( Output ) properties.get( "out" ) ) ); Object binding = this.newGroovyBinding( properties ); Method runMethod = groovyScriptEngine.getClass().getMethod( "run", String.class, binding.getClass() ); runMethod.invoke( groovyScriptEngine, scriptName + ".groovy", binding ); } private Object newGroovyBinding( Map<String, Object> properties ) throws Exception { Class<?> cls = Class.forName( BINDING_CLASS ); Object binding = cls.newInstance(); Method setPropertyMethod = cls.getMethod( "setProperty", String.class, Object.class ); for ( String key : properties.keySet() ) { setPropertyMethod.invoke( binding, key, properties.get( key ) ); } return binding; } @Override protected Object newInterpreter( String[] paths ) throws Exception { Class<?> cls = Class.forName( ENGINE_CLASS ); return cls.getConstructor( String[].class ).newInstance( new Object[] { paths } ); } @Override protected void ensureDependenciesAreInClasspath() throws Exception { Class.forName( BINDING_CLASS ); } /** * A wrapper for a supplied {@link Output} to correct a bug where a call * to "println" or "print" with a GString or another object would use * System.out instead of the right output instance. */ public static class GshOutput implements Output { private Output source; GshOutput( Output output ) { this.source = output; } public void print( Serializable object ) throws RemoteException { source.print( object ); } public void println( Serializable object ) throws RemoteException { source.println( object ); } public Appendable append( char c ) throws IOException { return source.append( c ); } public Appendable append( CharSequence csq, int start, int end ) throws IOException { return source.append( csq, start, end ); } public Appendable append( CharSequence csq ) throws IOException { return source.append( csq ); } /** * Prints an object to the wrapped {@link Output}. * @param object the object to print. * @throws RemoteException RMI error. */ public void print( Object object ) throws RemoteException { source.print( object.toString() ); } public void println() throws RemoteException { source.println(); } /** * Prints an object to the wrapped {@link Output}. * @param object the object to print. * @throws RemoteException RMI error. */ public void println( Object object ) throws RemoteException { source.println( object.toString() ); } } }
false
community_shell_src_main_java_org_neo4j_shell_apps_extra_GshExecutor.java
1,576
public class Gsh extends AbstractApp { public Continuation execute( AppCommandParser parser, Session session, Output out ) throws Exception { String line = parser.getLineWithoutApp(); new GshExecutor().execute( line, session, out ); return Continuation.INPUT_COMPLETE; } @Override public String getDescription() { GshExecutor anExecutor = new GshExecutor(); return "Runs groovy scripts. Usage: gsh <groovy script line>\n" + "Example: gsh --doSomething arg1 \"arg 2\" " + "--doSomethingElse arg1\n\n" + "Groovy scripts doSomething.groovy and " + "doSomethingElse.groovy must exist " + "in one of environment variable " + anExecutor.getPathKey() + " paths (default is " + anExecutor.getDefaultPaths() + ")"; } }
false
community_shell_src_main_java_org_neo4j_shell_apps_extra_Gsh.java
1,577
public class NoopApp extends AbstractApp { @Override public Continuation execute( AppCommandParser parser, Session session, Output out ) throws Exception { return Continuation.INPUT_COMPLETE; } }
false
community_shell_src_main_java_org_neo4j_shell_apps_NoopApp.java
1,578
@Service.Implementation( App.class ) public class Man extends AbstractApp { public static final int CONSOLE_WIDTH = 80; private static Collection<String> availableCommands; public Man() { addOptionDefinition( "l", new OptionDefinition( OptionValueType.NONE, "Display the commands in a vertical list" ) ); } public Continuation execute( AppCommandParser parser, Session session, Output out ) throws Exception { if ( parser.arguments().size() == 0 ) { boolean list = parser.options().containsKey( "l" ); printHelpString( out, getServer(), list ); return Continuation.INPUT_COMPLETE; } App app = this.getApp( parser ); out.println( "" ); for ( String line : splitDescription( fixDesciption( app.getDescription() ), CONSOLE_WIDTH ) ) { out.println( line ); } println( out, "" ); boolean hasOptions = false; for ( String option : app.getAvailableOptions() ) { hasOptions = true; String description = fixDesciption( app.getDescription( option ) ); String[] descriptionLines = splitDescription( description, CONSOLE_WIDTH ); for ( int i = 0; i < descriptionLines.length; i++ ) { String line = ""; if ( i == 0 ) { String optionPrefix = option.length() > 1 ? "--" : "-"; line = optionPrefix + option; } line += "\t "; line += descriptionLines[ i ]; println( out, line ); } } if ( hasOptions ) { println( out, "" ); } return Continuation.INPUT_COMPLETE; } private static String[] splitDescription( String description, int maxLength ) { List<String> lines = new ArrayList<String>(); while ( description.length() > 0 ) { String line = description.substring( 0, Math.min( maxLength, description.length() ) ); int position = line.indexOf( "\n" ); if ( position > -1 ) { line = description.substring( 0, position ); lines.add( line ); description = description.substring( position ); if ( description.length() > 0 ) { description = description.substring( 1 ); } } else { position = description.length() > maxLength ? findSpaceBefore( description, maxLength ) : description.length(); line = description.substring( 0, position ); lines.add( line ); description = description.substring( position ); } } return lines.toArray( new String[lines.size()] ); } private static int findSpaceBefore( String description, int position ) { while ( !Character.isWhitespace( description.charAt( position ) ) ) { position--; } return position + 1; } private static String getShortUsageString() { return "man <command>"; } private String fixDesciption( String description ) { if ( description == null ) { description = ""; } else if ( !description.endsWith( "." ) ) { description = description + "."; } return description; } private void println( Output out, String string ) throws RemoteException { out.println( " " + string ); } private App getApp( AppCommandParser parser ) throws Exception { String appName = parser.arguments().get( 0 ).toLowerCase(); App app = this.getServer().findApp( appName ); if ( app == null ) { throw new ShellException( "No manual entry for '" + appName + "'" ); } return app; } @Override public String getDescription() { return "Display a manual for a command or a general help message.\n" + "Usage: " + getShortUsageString(); } /** * Utility method for getting a short help string for a server. Basically it * contains an introductory message and also lists all available apps for * the server. * * @param server * the server to ask for * @return the short introductory help string. */ public static void printHelpString( Output out, ShellServer server, boolean list ) throws ShellException, RemoteException { String header = "Available commands:"; if ( list ) { out.println( header ); out.println(); for ( String command : server.getAllAvailableCommands() ) { out.println( " " + command ); } out.println(); } else { out.println( header + " " + availableCommandsAsString( server ) ); } out.println( "Use " + getShortUsageString() + " for info about each command." ); } /** * Uses {@link ClassLister} to list apps available at the server. * * @param server * the {@link ShellServer}. * @return a list of available commands a client can execute, whre the * server is an {@link AppShellServer}. */ public static synchronized Collection<String> getAvailableCommands( ShellServer server ) { if ( availableCommands == null ) { Collection<String> list = new ArrayList<String>(); // TODO Shouldn't trust the server to be an AbstractAppServer for ( String name : ( ( AbstractAppServer ) server ) .getAllAvailableCommands() ) { list.add( name ); } availableCommands = list; } return availableCommands; } private static synchronized String availableCommandsAsString( ShellServer server ) { StringBuffer commands = new StringBuffer(); for ( String command : getAvailableCommands( server ) ) { if ( commands.length() > 0 ) { commands.append( " " ); } commands.append( command ); } return commands.toString(); } }
false
community_shell_src_main_java_org_neo4j_shell_apps_Man.java
1,579
@Service.Implementation( App.class ) public class Help extends Man { }
false
community_shell_src_main_java_org_neo4j_shell_apps_Help.java
1,580
@Service.Implementation(App.class) public class Export extends AbstractApp { @Override public String getDescription() { return "Sets an environment variable. Usage: export <key>=<value>\n" + "F.ex: export NAME=\"Mattias Persson\". Variable names have " + "to be valid identifiers."; } public static Pair<String, String> splitInKeyEqualsValue( String string ) throws ShellException { int index = string.indexOf( '=' ); if ( index == -1 ) { throw new ShellException( "Invalid format <key>=<value>" ); } String key = string.substring( 0, index ); String value = string.substring( index + 1 ); return Pair.of( key, value ); } @Override public Continuation execute( AppCommandParser parser, Session session, Output out ) throws ShellException { Pair<String, String> keyValue = splitInKeyEqualsValue( parser.getLineWithoutApp() ); String key = keyValue.first(); String valueString = keyValue.other(); if ( session.has( valueString ) ) { Object value = session.get( valueString ); session.set( key, value ); return Continuation.INPUT_COMPLETE; } Object value = JSONParser.parse( valueString ); value = stripFromQuotesIfString( value ); if ( value instanceof String && value.toString().isEmpty() ) { session.remove( key ); } else { session.set( key, value ); } return Continuation.INPUT_COMPLETE; } private Object stripFromQuotesIfString( Object value ) { return value instanceof String ? stripFromQuotes( value.toString() ) : value; } }
false
community_shell_src_main_java_org_neo4j_shell_apps_Export.java
1,581
@Service.Implementation( App.class ) public class Env extends AbstractApp { @Override public String getDescription() { return "Lists all environment variables"; } public Continuation execute( AppCommandParser parser, Session session, Output out ) throws Exception { for ( String key : session.keys() ) { Object value = session.get( key ); out.println( key + "=" + ( value == null ? "" : value ) ); } return Continuation.INPUT_COMPLETE; } }
false
community_shell_src_main_java_org_neo4j_shell_apps_Env.java
1,582
@Service.Implementation(App.class) public class Alias extends AbstractApp { @Override public String getDescription() { return "Adds an alias so that it can be used later as a command.\n" + "Usage: alias <key>=<value>"; } public Continuation execute( AppCommandParser parser, Session session, Output out ) throws Exception { String line = parser.getLineWithoutApp(); if ( line.trim().length() == 0 ) { printAllAliases( session, out ); return Continuation.INPUT_COMPLETE; } Pair<String, String> keyValue = Export.splitInKeyEqualsValue( line ); String key = keyValue.first(); String value = keyValue.other(); if ( value == null || value.trim().length() == 0 ) { session.removeAlias( key ); } else { session.setAlias( key, value ); } return Continuation.INPUT_COMPLETE; } private void printAllAliases( Session session, Output out ) throws Exception { for ( String key : session.getAliasKeys() ) { out.println( "alias " + key + "='" + session.getAlias( key ) + "'" ); } } }
false
community_shell_src_main_java_org_neo4j_shell_apps_Alias.java
1,583
public class Welcome implements Serializable { private final String message; private final Serializable id; private final String prompt; public Welcome( String message, Serializable id, String prompt ) { this.message = message; this.id = id; this.prompt = prompt; } public String getMessage() { return message; } public Serializable getId() { return id; } public String getPrompt() { return prompt; } }
false
community_shell_src_main_java_org_neo4j_shell_Welcome.java
1,584
public class Variables { /** * The {@link org.neo4j.shell.Session} key to use to store the current node and working * directory (i.e. the path which the client got to it). */ public static final String WORKING_DIR_KEY = "WORKING_DIR"; public static final String CURRENT_KEY = "CURRENT_DIR"; private static final Pattern IDENTIFIER = Pattern.compile( "^\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*$" ); public static final String TX_COUNT = "TX_COUNT"; /** * The session key for the prompt key, just like in Bash. */ public static final String PROMPT_KEY = "PS1"; /** * The session key for whether or not to print stack traces for exceptions. */ public static final String STACKTRACES_KEY = "STACKTRACES"; /** * When displaying node ids this variable is also used for getting an * appropriate property value from that node to display as the title. * This variable can contain many property keys (w/ regex) separated by * comma prioritized in order. */ public static final String TITLE_KEYS_KEY = "TITLE_KEYS"; /** * The maximum length of titles to be displayed. */ public static final String TITLE_MAX_LENGTH = "TITLE_MAX_LENGTH"; /** * @param key a variable name * @throws org.neo4j.shell.ShellException if key doesn't match a valid identifier name */ public static void checkIsValidVariableName( String key ) throws ShellException { if (!isIdentifier( key ) ) throw new ShellException( key + " is no valid variable name. May only contain " + "alphanumeric characters and underscores."); } public static boolean isIdentifier( String key ) { return IDENTIFIER.matcher( key ).matches(); } }
false
community_shell_src_main_java_org_neo4j_shell_Variables.java
1,585
private abstract class Tester implements Runnable { private final String name; ShellClient client; private boolean alive = true; private Exception exception = null; protected Tester( String name ) { this.name = name; try { client = new SameJvmClient( new HashMap<String, Serializable>(), server, new SilentLocalOutput() ); } catch ( ShellException e ) { throw new RuntimeException( "Error starting client", e ); } } protected void execute( String cmd ) throws Exception { executeCommand( server, client, cmd ); Thread.sleep( r.nextInt( 10 ) ); } @Override public void run() { try { while ( alive ) { doStuff(); } } catch ( Exception e ) { alive = false; exception = e; } } public void die() throws Exception { if ( exception != null ) { throw exception; } alive = false; } protected abstract void doStuff() throws Exception; private String name() { return name; } }
false
community_shell_src_test_java_org_neo4j_shell_TransactionSoakIT.java
1,586
private class Rollbacker extends Tester { private Rollbacker( String name ) { super( name ); } @Override protected void doStuff() throws Exception { execute( "begin transaction" ); execute( "create (a {name:'a'}), (b {name:'b'}), a-[:LIKES]->b;" ); execute( "rollback" ); } }
false
community_shell_src_test_java_org_neo4j_shell_TransactionSoakIT.java
1,587
private class Reader extends Tester { public Reader( String name ) { super(name); } @Override protected void doStuff() throws Exception { execute( "match n return count(n.name);" ); } }
false
community_shell_src_test_java_org_neo4j_shell_TransactionSoakIT.java
1,588
private class Committer extends Tester { private int count = 0; private Committer( String name ) { super( name ); } @Override protected void doStuff() throws Exception { execute( "begin transaction" ); execute( "create (a {name:'a'}), (b {name:'b'}), a-[:LIKES]->b;" ); execute( "commit" ); count = count + 1; } }
false
community_shell_src_test_java_org_neo4j_shell_TransactionSoakIT.java
1,589
@Ignore("Jake 2013-09-13: Exposes bug that will be fixed by kernel API") public class TransactionSoakIT { protected GraphDatabaseAPI db; private ShellServer server; private final Random r = new Random( System.currentTimeMillis() ); @Before public void doBefore() throws Exception { db = (GraphDatabaseAPI)new TestGraphDatabaseFactory().newImpermanentDatabase(); server = new GraphDatabaseShellServer( db ); } @After public void doAfter() throws Exception { server.shutdown(); db.shutdown(); } @Test public void multiThreads() throws Exception { List<Tester> testers = createTesters(); List<Thread> threads = startTesters( testers ); Thread.sleep( 10000 ); stopTesters( testers ); waitForThreadsToFinish( threads ); try ( Transaction tx = db.beginTx() ) { long relationshipCount = count( GlobalGraphOperations.at( db ).getAllRelationships() ); int expected = committerCount( testers ); assertEquals( expected, relationshipCount ); } } private List<Tester> createTesters() throws Exception { List<Tester> testers = new ArrayList<>( 20 ); for ( int i = 0; i < 20; i++ ) { int x = r.nextInt( 3 ); Tester t; if ( x == 0 ) { t = new Reader("Reader-" + i); } else if ( x == 1 ) { t = new Committer("Committer-" + i); } else if ( x == 2 ) { t = new Rollbacker("Rollbacker-" + i); } else { throw new Exception( "oh noes" ); } testers.add( t ); } return testers; } private int committerCount( List<Tester> testers ) { int count = 0; for ( Tester t : testers ) { if ( t instanceof Committer ) { Committer c = (Committer) t; count = count + c.count; } } return count; } private void waitForThreadsToFinish( List<Thread> threads ) throws InterruptedException { for ( Thread t : threads ) { t.join(); } } private void stopTesters( List<Tester> testers ) throws Exception { for ( Tester t : testers ) { t.die(); } } private List<Thread> startTesters( List<Tester> testers ) { List<Thread> threads = new ArrayList<Thread>(); for ( Tester t : testers ) { Thread thread = new Thread( t, t.name() ); thread.start(); threads.add( thread ); } return threads; } private class Reader extends Tester { public Reader( String name ) { super(name); } @Override protected void doStuff() throws Exception { execute( "match n return count(n.name);" ); } } private class Committer extends Tester { private int count = 0; private Committer( String name ) { super( name ); } @Override protected void doStuff() throws Exception { execute( "begin transaction" ); execute( "create (a {name:'a'}), (b {name:'b'}), a-[:LIKES]->b;" ); execute( "commit" ); count = count + 1; } } private class Rollbacker extends Tester { private Rollbacker( String name ) { super( name ); } @Override protected void doStuff() throws Exception { execute( "begin transaction" ); execute( "create (a {name:'a'}), (b {name:'b'}), a-[:LIKES]->b;" ); execute( "rollback" ); } } private abstract class Tester implements Runnable { private final String name; ShellClient client; private boolean alive = true; private Exception exception = null; protected Tester( String name ) { this.name = name; try { client = new SameJvmClient( new HashMap<String, Serializable>(), server, new SilentLocalOutput() ); } catch ( ShellException e ) { throw new RuntimeException( "Error starting client", e ); } } protected void execute( String cmd ) throws Exception { executeCommand( server, client, cmd ); Thread.sleep( r.nextInt( 10 ) ); } @Override public void run() { try { while ( alive ) { doStuff(); } } catch ( Exception e ) { alive = false; exception = e; } } public void die() throws Exception { if ( exception != null ) { throw exception; } alive = false; } protected abstract void doStuff() throws Exception; private String name() { return name; } } public void executeCommand( ShellServer server, ShellClient client, String command ) throws Exception { CollectingOutput output = new CollectingOutput(); server.interpretLine( client.getId(), command, output ); } }
false
community_shell_src_test_java_org_neo4j_shell_TransactionSoakIT.java
1,590
public class TextUtil { public static String templateString( String templateString, Map<String, ? extends Object> data ) { return templateString( templateString, "\\$", data ); } public static String templateString( String templateString, String variablePrefix, Map<String, ? extends Object> data ) { // Sort data strings on length. Map<Integer, List<String>> lengthMap = new HashMap<Integer, List<String>>(); int longest = 0; for ( String key : data.keySet() ) { int length = key.length(); if ( length > longest ) { longest = length; } List<String> innerList = null; Integer innerKey = Integer.valueOf( length ); if ( lengthMap.containsKey( innerKey ) ) { innerList = lengthMap.get( innerKey ); } else { innerList = new ArrayList<String>(); lengthMap.put( innerKey, innerList ); } innerList.add( key ); } // Replace it. String result = templateString; for ( int i = longest; i >= 0; i-- ) { Integer lengthKey = Integer.valueOf( i ); if ( !lengthMap.containsKey( lengthKey ) ) { continue; } List<String> list = lengthMap.get( lengthKey ); for ( String key : list ) { Object value = data.get( key ); if ( value != null ) { String replacement = data.get( key ).toString(); String regExpMatchString = variablePrefix + key; result = result.replaceAll( regExpMatchString, replacement ); } } } return result; } public static String lastWordOrQuoteOf( String text, boolean preserveQuotation ) { String[] quoteParts = text.split( "\"" ); String lastPart = quoteParts[quoteParts.length-1]; boolean isWithinQuotes = quoteParts.length % 2 == 0; String lastWord = null; if ( isWithinQuotes ) { lastWord = lastPart; if ( preserveQuotation ) { lastWord = "\"" + lastWord + (text.endsWith( "\"" ) ? "\"" : "" ); } } else { String[] lastPartParts = splitAndKeepEscapedSpaces( lastPart, preserveQuotation ); lastWord = lastPartParts[lastPartParts.length-1]; } return lastWord; } public static String[] splitAndKeepEscapedSpaces( String string, boolean preserveEscapes ) { Collection<String> result = new ArrayList<String>(); StringBuilder current = new StringBuilder(); for ( int i = 0; i < string.length(); i++ ) { char ch = string.charAt( i ); if ( ch == ' ' ) { boolean isGluedSpace = i > 0 && string.charAt( i-1 ) == '\\'; if ( !isGluedSpace ) { result.add( current.toString() ); current = new StringBuilder(); continue; } } if ( preserveEscapes || ch != '\\' ) { current.append( ch ); } } if ( current.length() > 0 ) { result.add( current.toString() ); } return result.toArray( new String[result.size()] ); } public static String multiplyString( String string, int times ) { StringBuilder result = new StringBuilder(); for ( int i = 0; i < times; i++ ) result.append( string ); return result.toString(); } public static String removeSpaces( String command ) { while ( command.length() > 0 && command.charAt( 0 ) == ' ' ) command = command.substring( 1 ); while ( command.length() > 0 && command.charAt( command.length()-1 ) == ' ' ) command = command.substring( 0, command.length()-1 ); return command; } /** * Tokenizes a string, regarding quotes. * * @param string the string to tokenize. * @return the tokens from the line. */ public static String[] tokenizeStringWithQuotes( String string ) { return tokenizeStringWithQuotes( string, true ); } /** * Tokenizes a string, regarding quotes. Examples: * * o '"One two"' ==> [ "One two" ] * o 'One two' ==> [ "One", "two" ] * o 'One "two three" four' ==> [ "One", "two three", "four" ] * * @param string the string to tokenize. * @param trim whether or not to trim each token. * @return the tokens from the line. */ public static String[] tokenizeStringWithQuotes( String string, boolean trim ) { if ( trim ) { string = string.trim(); } ArrayList<String> result = new ArrayList<String>(); string = string.trim(); boolean inside = string.startsWith( "\"" ); StringTokenizer quoteTokenizer = new StringTokenizer( string, "\"" ); while ( quoteTokenizer.hasMoreTokens() ) { String token = quoteTokenizer.nextToken(); if ( trim ) { token = token.trim(); } if ( token.length() == 0 ) { // Skip it } else if ( inside ) { // Don't split result.add( token ); } else { Collections.addAll( result, TextUtil.splitAndKeepEscapedSpaces( token, false ) ); } inside = !inside; } return result.toArray( new String[result.size()] ); } public static String stripFromQuotes( String string ) { if ( string != null ) { if ( string.startsWith( "\"" ) && string.endsWith( "\"" ) ) { return string.substring( 1, string.length()-1 ); } } return string; } }
false
community_shell_src_main_java_org_neo4j_shell_TextUtil.java
1,591
public class TestTransactionApps { protected GraphDatabaseAPI db; private FakeShellServer shellServer; private ShellClient shellClient; @Before public void doBefore() throws Exception { db = (GraphDatabaseAPI)new TestGraphDatabaseFactory().newImpermanentDatabase(); shellServer = new FakeShellServer( db ); shellClient = new SameJvmClient( new HashMap<String, Serializable>(), shellServer, new CollectingOutput() ); } @After public void doAfter() throws Exception { shellClient.shutdown(); shellServer.shutdown(); db.shutdown(); } @Test public void begin_transaction_opens_a_transaction() throws Exception { executeCommand( "begin transaction" ); assertWeAreInATransaction(); } @Test public void two_begin_tran_works_as_expected() throws Exception { executeCommand( "begin tran" ); executeCommand( "begin transaction" ); assertWeAreInATransaction(); } @Test public void multiple_begins_and_commits_work() throws Exception { executeCommand( "begin transaction" ); executeCommand( "begin" ); executeCommand( "begin transaction" ); executeCommand( "commit" ); executeCommand( "commit" ); executeCommand( "commit" ); assertWeAreNotInATransaction(); } @Test public void commit_tran_closes_open_transaction() throws Exception { executeCommand( "begin transaction" ); executeCommand( "commit" ); assertWeAreNotInATransaction(); } @Test public void already_in_transaction() throws Exception { db.beginTx(); executeCommand( "begin transaction" ); executeCommand( "commit" ); assertWeAreInATransaction(); } @Test public void rollback_rolls_everything_back() throws Exception { db.beginTx(); executeCommand( "begin transaction" ); executeCommand( "begin transaction" ); executeCommand( "begin transaction" ); executeCommand( "rollback" ); assertWeAreNotInATransaction(); } @Test public void rollback_outside_of_transaction_fails() throws Exception { executeCommandExpectingException( "rollback", "Not in a transaction" ); } private void assertWeAreNotInATransaction() throws SystemException { assertTrue( "Expected to not be in a transaction", shellServer.getActiveTransactionCount() == 0 ); } private void assertWeAreInATransaction() throws SystemException { assertTrue( "Expected to be in a transaction", shellServer.getActiveTransactionCount() > 0 ); } 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 + "'" ); } } } }
false
community_shell_src_test_java_org_neo4j_shell_TestTransactionApps.java
1,592
public class CdTest { @Test public void shouldProvideTabCompletions() throws Exception { // GIVEN Node root = createNodeWithSomeSubNodes( "Mattias", "Magnus", "Tobias" ); Cd app = (Cd) server.findApp( "cd" ); app.execute( new AppCommandParser( server, "cd -a " + root.getId() ), session, silence ); // WHEN List<String> candidates = app.completionCandidates( "cd Ma", session ); // THEN assertHasCandidate( candidates, "Mattias" ); assertHasCandidate( candidates, "Magnus" ); } private void assertHasCandidate( List<String> candidates, String shouldStartWith ) { boolean found = false; for ( String candidate : candidates ) { if ( candidate.startsWith( shouldStartWith ) ) { found = true; } } assertTrue( "Should have found a candidate among " + candidates + " starting with '" + shouldStartWith + "'", found ); } private Node createNodeWithSomeSubNodes( String... names ) { GraphDatabaseService db = dbRule.getGraphDatabaseService(); try ( Transaction tx = db.beginTx() ) { Node root = db.createNode(); for ( String name : names ) { Node node = db.createNode(); node.setProperty( "name", name ); root.createRelationshipTo( node, MyRelTypes.TEST ); } tx.success(); return root; } } private final Output silence = new SilentLocalOutput(); private final Session session = new Session( "test" ); public final @Rule DatabaseRule dbRule = new ImpermanentDatabaseRule(); private GraphDatabaseAPI db; private GraphDatabaseShellServer server; @Before public void setup() throws Exception { db = dbRule.getGraphDatabaseAPI(); server = new GraphDatabaseShellServer( db ); session.set( Variables.TITLE_KEYS_KEY, "name" ); } @After public void shutdown() throws Exception { server.shutdown(); } }
false
community_shell_src_test_java_org_neo4j_shell_kernel_apps_CdTest.java
1,593
public class Dbinfo extends NonTransactionProvidingApp { { addOptionDefinition( "l", new OptionDefinition( OptionValueType.MAY, "List available attributes for the specified bean. " + "Including a description about each attribute." ) ); addOptionDefinition( "g", new OptionDefinition( OptionValueType.MUST, "Get the value of the specified attribute(s), " + "or all attributes of the specified bean " + "if no attributes are specified." ) ); } @Override public String getDescription() { final Kernel kernel; try { kernel = getKernel(); } catch ( ShellException e ) { return e.getMessage(); } MBeanServer mbeans = getPlatformMBeanServer(); StringBuilder result = new StringBuilder( "Get runtime information about the Graph Database.\n" + "This uses the Neo4j management beans to get" + " information about the Graph Database.\n\n" ); availableBeans( mbeans, kernel, result ); result.append( "\n" ); getUsage( result ); return result.toString(); } private void getUsage( StringBuilder result ) { result.append( "USAGE: " ); result.append( getName() ); result.append( " -(g|l) <bean name> [list of attribute names]" ); } private Kernel getKernel() throws ShellException { GraphDatabaseAPI graphDb = getServer().getDb(); Kernel kernel = null; if ( graphDb instanceof GraphDatabaseAPI ) { try { kernel = graphDb.getDependencyResolver().resolveDependency( JmxKernelExtension.class ).getSingleManagementBean( Kernel.class ); } catch ( Exception e ) { // Ignore - the null check does the work } } if ( kernel == null ) { throw new ShellException( getName() + " is not available for this graph database." ); } return kernel; } @Override protected Continuation exec( AppCommandParser parser, Session session, Output out ) throws Exception { Kernel kernel = getKernel(); boolean list = parser.options().containsKey( "l" ), get = parser.options().containsKey( "g" ); if ( (list && get) || (!list && !get) ) { StringBuilder usage = new StringBuilder(); getUsage( usage ); usage.append( ".\n" ); out.print( usage.toString() ); return Continuation.INPUT_COMPLETE; } MBeanServer mbeans = getPlatformMBeanServer(); String bean = null; String[] attributes = null; if ( list ) { bean = parser.options().get( "l" ); } else if ( get ) { bean = parser.options().get( "g" ); attributes = parser.arguments().toArray( new String[parser.arguments().size()] ); } if ( bean == null ) // list beans { StringBuilder result = new StringBuilder(); availableBeans( mbeans, kernel, result ); out.print( result.toString() ); return Continuation.INPUT_COMPLETE; } ObjectName mbean; { mbean = kernel.getMBeanQuery(); Hashtable<String, String> properties = new Hashtable<String, String>( mbean.getKeyPropertyList() ); properties.put( "name", bean ); try { Iterator<ObjectName> names = mbeans.queryNames( new ObjectName( mbean.getDomain(), properties ), null ).iterator(); if ( names.hasNext() ) { mbean = names.next(); if ( names.hasNext() ) { mbean = null; } } else { mbean = null; } } catch ( Exception e ) { mbean = null; } } if ( mbean == null ) { throw new ShellException( "No such management bean \"" + bean + "\"." ); } if ( attributes == null ) // list attributes { for ( MBeanAttributeInfo attr : mbeans.getMBeanInfo( mbean ).getAttributes() ) { out.println( attr.getName() + " - " + attr.getDescription() ); } } else { if ( attributes.length == 0 ) // specify all attributes { MBeanAttributeInfo[] allAttributes = mbeans.getMBeanInfo( mbean ).getAttributes(); attributes = new String[allAttributes.length]; for ( int i = 0; i < allAttributes.length; i++ ) { attributes[i] = allAttributes[i].getName(); } } JSONObject json = new JSONObject(); for ( Object value : mbeans.getAttributes( mbean, attributes ) ) { printAttribute( json, value ); } out.println( json.toString( 2 ) ); } return Continuation.INPUT_COMPLETE; } private void printAttribute( JSONObject json, Object value ) throws RemoteException, ShellException { try { Attribute attribute = (Attribute) value; Object attributeValue = attribute.getValue(); if ( attributeValue != null && attributeValue.getClass().isArray() ) { Object[] arrayValue = (Object[]) attributeValue; JSONArray array = new JSONArray(); for ( Object item : (Object[]) arrayValue ) { if ( item instanceof CompositeData ) { array.put( compositeDataAsMap( (CompositeData) item ) ); } else { array.put( item.toString() ); } } json.put( attribute.getName(), array ); } else { json.put( attribute.getName(), attributeValue ); } } catch ( JSONException e ) { throw ShellException.wrapCause( e ); } } private Map<?, ?> compositeDataAsMap( CompositeData item ) { Map<String, Object> result = new HashMap<String, Object>(); CompositeData compositeData = (CompositeData) item; for ( String key : compositeData.getCompositeType().keySet() ) { result.put( key, compositeData.get( key ) ); } return result; } private void availableBeans( MBeanServer mbeans, Kernel kernel, StringBuilder result ) { result.append( "Available Management Beans\n" ); for ( Object name : mbeans.queryNames( kernel.getMBeanQuery(), null ) ) { result.append( "* " ); result.append( ((ObjectName) name).getKeyProperty( "name" ) ); result.append( "\n" ); } } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_Dbinfo.java
1,594
public class DontShutdownLocalServer { public static void main( String[] args ) throws Exception { GraphDatabaseShellServer server = new GraphDatabaseShellServer( args[0], false, null ); // Intentionally don't shutdown the server } }
false
community_shell_src_test_java_org_neo4j_shell_DontShutdownLocalServer.java
1,595
public class AssertEventually { public static void assertEventually( String message, int timeoutSeconds, Condition condition ) { long startTime = System.currentTimeMillis(); while ( ! condition.evaluate() ) { long currentTime = System.currentTimeMillis(); if ( currentTime - startTime > timeoutSeconds * 1000 ) { fail( format( "Condition '%s' was not true after %s seconds.", message, timeoutSeconds ) ); } try { Thread.sleep( 100 ); } catch ( InterruptedException ignored ) { } } } public interface Condition { boolean evaluate(); } }
false
community_kernel_src_test_java_org_neo4j_test_AssertEventually.java
1,596
public class Progressor { private final long nanos; private Progressor( long nanos ) { this.nanos = nanos; } public void tick() { progress( nanos ); } }
false
community_kernel_src_test_java_org_neo4j_test_ArtificialClock.java
1,597
public class ArtificialClock implements Clock { private volatile long currentTimeNanos; @Override public long currentTimeMillis() { return NANOSECONDS.toMillis( currentTimeNanos ); } public Progressor progressor( long time, TimeUnit unit ) { return new Progressor( unit.toNanos( time ) ); } public void progress( long time, TimeUnit unit ) { progress( unit.toNanos( time ) ); } private synchronized void progress( long nanos ) { currentTimeNanos += nanos; } public class Progressor { private final long nanos; private Progressor( long nanos ) { this.nanos = nanos; } public void tick() { progress( nanos ); } } }
false
community_kernel_src_test_java_org_neo4j_test_ArtificialClock.java
1,598
{ @Override public NEXT apply( FROM from ) { return function.apply( AlgebraicFunction.this.apply( from ) ); } };
false
community_kernel_src_test_java_org_neo4j_test_AlgebraicFunction.java
1,599
public abstract class AlgebraicFunction<FROM, TO> implements Function<FROM, TO> { public <NEXT> AlgebraicFunction<FROM, NEXT> then( final Function<TO, NEXT> function ) { return new AlgebraicFunction<FROM, NEXT>( repr + " then " + function.toString() ) { @Override public NEXT apply( FROM from ) { return function.apply( AlgebraicFunction.this.apply( from ) ); } }; } public AlgebraicFunction() { String repr = getClass().getSimpleName(); if ( getClass().isAnonymousClass() ) { for ( StackTraceElement trace : Thread.currentThread().getStackTrace() ) { if ( trace.getClassName().equals( Thread.class.getName() ) && trace.getMethodName().equals( "getStackTrace" ) ) { continue; } if ( trace.getClassName().equals( AlgebraicFunction.class.getName() ) ) { continue; } if ( trace.getClassName().equals( getClass().getName() ) ) { continue; } repr = trace.getMethodName(); break; } } this.repr = repr; } private final String repr; private AlgebraicFunction( String repr ) { this.repr = repr; } @Override public String toString() { return repr; } }
false
community_kernel_src_test_java_org_neo4j_test_AlgebraicFunction.java