Unnamed: 0
int64
0
6.7k
func
stringlengths
12
89.6k
target
bool
2 classes
project
stringlengths
45
151
1,600
{ @Override public void run() { try { task.run( graphdb ); } catch ( RuntimeException e ) { e.addSuppressed( stackTraceOfOrigin ); throw e; } } }, task.toString() ).start();
false
community_kernel_src_test_java_org_neo4j_test_AbstractSubProcessTestBase.java
1,601
@SuppressWarnings("serial") private static class ThreadTask implements Task { private final Task task; private final Exception stackTraceOfOrigin; ThreadTask( Task task ) { this.task = task; this.stackTraceOfOrigin = new Exception("Stack trace of thread that created this ThreadTask"); } @Override public void run( final GraphDatabaseAPI graphdb ) { new Thread( new Runnable() { @Override public void run() { try { task.run( graphdb ); } catch ( RuntimeException e ) { e.addSuppressed( stackTraceOfOrigin ); throw e; } } }, task.toString() ).start(); } }
false
community_kernel_src_test_java_org_neo4j_test_AbstractSubProcessTestBase.java
1,602
@SuppressWarnings({"hiding", "serial"}) private static class SubInstance extends SubProcess<Instance, Bootstrapper> implements Instance { private volatile GraphDatabaseAPI graphdb; private static final AtomicReferenceFieldUpdater<SubInstance, GraphDatabaseAPI> GRAPHDB = AtomicReferenceFieldUpdater .newUpdater( SubInstance.class, GraphDatabaseAPI.class, "graphdb" ); private volatile Bootstrapper bootstrap; private volatile Throwable failure; @Override protected synchronized void startup( Bootstrapper bootstrap ) { this.bootstrap = bootstrap; try { graphdb = (GraphDatabaseAPI) bootstrap.startup(); } catch ( Throwable failure ) { this.failure = failure; } } @Override public void awaitStarted() throws InterruptedException { while ( graphdb == null ) { Throwable failure = this.failure; if ( failure != null ) { throw new StartupFailureException( failure ); } Thread.sleep( 1 ); } } @Override public void run( Task task ) { task.run( graphdb ); } @Override protected void shutdown( boolean normal ) { GraphDatabaseService graphdb; Bootstrapper bootstrap = this.bootstrap; graphdb = GRAPHDB.getAndSet( this, null ); this.bootstrap = null; if ( graphdb != null ) { bootstrap.shutdown( graphdb, normal ); } super.shutdown( normal ); } @Override public void restart() { GraphDatabaseService graphdb; Bootstrapper bootstrap = this.bootstrap; while ( (graphdb = GRAPHDB.getAndSet( this, null )) == null ) { if ( (bootstrap = this.bootstrap) == null ) { throw new IllegalStateException( "instance has been shut down" ); } } graphdb.shutdown(); this.graphdb = (GraphDatabaseAPI) bootstrap.startup(); } }
false
community_kernel_src_test_java_org_neo4j_test_AbstractSubProcessTestBase.java
1,603
@SuppressWarnings("serial") private static class StartupFailureException extends RuntimeException { StartupFailureException( Throwable failure ) { super( failure ); } }
false
community_kernel_src_test_java_org_neo4j_test_AbstractSubProcessTestBase.java
1,604
public static class KillAwareBootstrapper extends Bootstrapper { public KillAwareBootstrapper( AbstractSubProcessTestBase test, int instance, Map<String, String> dbConfiguration ) throws IOException { super( test, instance, dbConfiguration ); } @Override protected void shutdown( GraphDatabaseService graphdb, boolean normal ) { if ( normal ) { super.shutdown( graphdb, normal ); } } }
false
community_kernel_src_test_java_org_neo4j_test_AbstractSubProcessTestBase.java
1,605
@SuppressWarnings("serial") public static class Bootstrapper implements Serializable { protected final String storeDir; private final Map<String, String> dbConfiguration; public Bootstrapper( AbstractSubProcessTestBase test, int instance ) throws IOException { this( test, instance, new HashMap<String, String>() ); } public Bootstrapper( AbstractSubProcessTestBase test, int instance, Map<String, String> dbConfiguration ) throws IOException { this.dbConfiguration = addVitalConfig( dbConfiguration ); this.storeDir = getStoreDir( test, instance ).getCanonicalPath(); } private Map<String, String> addVitalConfig( Map<String, String> dbConfiguration ) { return stringMap( new HashMap<>( dbConfiguration ), GraphDatabaseSettings.keep_logical_logs.name(), Settings.TRUE ); } protected GraphDatabaseService startup() { return new GraphDatabaseFactory().newEmbeddedDatabaseBuilder( storeDir ).setConfig( dbConfiguration ) .newGraphDatabase(); } protected void shutdown( GraphDatabaseService graphdb, boolean normal ) { graphdb.shutdown(); } }
false
community_kernel_src_test_java_org_neo4j_test_AbstractSubProcessTestBase.java
1,606
public class AbstractSubProcessTestBase { protected final TargetDirectory target; protected final Pair<Instance, BreakPoint[]>[] instances; public AbstractSubProcessTestBase() { this( 1 ); } @SuppressWarnings("unchecked") protected AbstractSubProcessTestBase( int instances ) { this.instances = new Pair[instances]; this.target = TargetDirectory.forTest( getClass() ); } protected final void runInThread( Task task ) { run( new ThreadTask( task ) ); } protected final void run( Task task ) { for ( Pair<Instance, BreakPoint[]> instance : instances ) { if ( instance != null ) { instance.first().run( task ); } } } protected final void restart() { for ( Pair<Instance, BreakPoint[]> instance : instances ) { if ( instance != null ) { instance.first().restart(); } } } /** * @param id the id of the instance to get breakpoints for */ protected BreakPoint[] breakpoints( int id ) { return null; } protected interface Task extends Serializable { void run( GraphDatabaseAPI graphdb ); } @Before public final void startSubprocesses() throws IOException, InterruptedException { SubInstance prototype = new SubInstance(); for ( int i = 0; i < instances.length; i++ ) { BreakPoint[] breakPoints = breakpoints( i ); instances[i] = Pair.of( prototype.start( bootstrap( i ), breakPoints ), breakPoints ); } for ( Pair<Instance, BreakPoint[]> instance : instances ) { if ( instance != null ) { instance.first().awaitStarted(); } } } protected Bootstrapper bootstrap( int id ) throws IOException { return bootstrap( id, new HashMap<String, String>() ); } protected Bootstrapper bootstrap( int id, Map<String, String> dbConfiguration ) throws IOException { return new Bootstrapper( this, id, dbConfiguration ); } @After public final void stopSubprocesses() { synchronized ( instances ) { for ( int i = 0; i < instances.length; i++ ) { Pair<Instance, BreakPoint[]> instance = instances[i]; if ( instance != null ) { SubProcess.stop( instance.first() ); } instances[i] = null; } } } public interface Instance { void run( Task task ); void awaitStarted() throws InterruptedException; void restart(); // <T> T getMBean( Class<T> beanType ); } @SuppressWarnings("serial") public static class Bootstrapper implements Serializable { protected final String storeDir; private final Map<String, String> dbConfiguration; public Bootstrapper( AbstractSubProcessTestBase test, int instance ) throws IOException { this( test, instance, new HashMap<String, String>() ); } public Bootstrapper( AbstractSubProcessTestBase test, int instance, Map<String, String> dbConfiguration ) throws IOException { this.dbConfiguration = addVitalConfig( dbConfiguration ); this.storeDir = getStoreDir( test, instance ).getCanonicalPath(); } private Map<String, String> addVitalConfig( Map<String, String> dbConfiguration ) { return stringMap( new HashMap<>( dbConfiguration ), GraphDatabaseSettings.keep_logical_logs.name(), Settings.TRUE ); } protected GraphDatabaseService startup() { return new GraphDatabaseFactory().newEmbeddedDatabaseBuilder( storeDir ).setConfig( dbConfiguration ) .newGraphDatabase(); } protected void shutdown( GraphDatabaseService graphdb, boolean normal ) { graphdb.shutdown(); } } protected static File getStoreDir( AbstractSubProcessTestBase test, int instance ) throws IOException { return test.target.cleanDirectory( "graphdb." + instance ); } protected static Bootstrapper killAwareBootstrapper( AbstractSubProcessTestBase test, int instance, Map<String, String> dbConfiguration ) { try { return new KillAwareBootstrapper( test, instance, dbConfiguration ); } catch ( IOException e ) { throw new RuntimeException( e ); } } public static class KillAwareBootstrapper extends Bootstrapper { public KillAwareBootstrapper( AbstractSubProcessTestBase test, int instance, Map<String, String> dbConfiguration ) throws IOException { super( test, instance, dbConfiguration ); } @Override protected void shutdown( GraphDatabaseService graphdb, boolean normal ) { if ( normal ) { super.shutdown( graphdb, normal ); } } } @SuppressWarnings("serial") private static class ThreadTask implements Task { private final Task task; private final Exception stackTraceOfOrigin; ThreadTask( Task task ) { this.task = task; this.stackTraceOfOrigin = new Exception("Stack trace of thread that created this ThreadTask"); } @Override public void run( final GraphDatabaseAPI graphdb ) { new Thread( new Runnable() { @Override public void run() { try { task.run( graphdb ); } catch ( RuntimeException e ) { e.addSuppressed( stackTraceOfOrigin ); throw e; } } }, task.toString() ).start(); } } @SuppressWarnings({"hiding", "serial"}) private static class SubInstance extends SubProcess<Instance, Bootstrapper> implements Instance { private volatile GraphDatabaseAPI graphdb; private static final AtomicReferenceFieldUpdater<SubInstance, GraphDatabaseAPI> GRAPHDB = AtomicReferenceFieldUpdater .newUpdater( SubInstance.class, GraphDatabaseAPI.class, "graphdb" ); private volatile Bootstrapper bootstrap; private volatile Throwable failure; @Override protected synchronized void startup( Bootstrapper bootstrap ) { this.bootstrap = bootstrap; try { graphdb = (GraphDatabaseAPI) bootstrap.startup(); } catch ( Throwable failure ) { this.failure = failure; } } @Override public void awaitStarted() throws InterruptedException { while ( graphdb == null ) { Throwable failure = this.failure; if ( failure != null ) { throw new StartupFailureException( failure ); } Thread.sleep( 1 ); } } @Override public void run( Task task ) { task.run( graphdb ); } @Override protected void shutdown( boolean normal ) { GraphDatabaseService graphdb; Bootstrapper bootstrap = this.bootstrap; graphdb = GRAPHDB.getAndSet( this, null ); this.bootstrap = null; if ( graphdb != null ) { bootstrap.shutdown( graphdb, normal ); } super.shutdown( normal ); } @Override public void restart() { GraphDatabaseService graphdb; Bootstrapper bootstrap = this.bootstrap; while ( (graphdb = GRAPHDB.getAndSet( this, null )) == null ) { if ( (bootstrap = this.bootstrap) == null ) { throw new IllegalStateException( "instance has been shut down" ); } } graphdb.shutdown(); this.graphdb = (GraphDatabaseAPI) bootstrap.startup(); } } @SuppressWarnings("serial") private static class StartupFailureException extends RuntimeException { StartupFailureException( Throwable failure ) { super( failure ); } } }
false
community_kernel_src_test_java_org_neo4j_test_AbstractSubProcessTestBase.java
1,607
{ @Override protected void config( GraphDatabaseBuilder builder, String clusterName, int serverId ) { super.config( builder, clusterName, serverId ); configureClusterMember( builder, clusterName, serverId ); } @Override protected void insertInitialData( GraphDatabaseService db, String name, int serverId ) { super.insertInitialData( db, name, serverId ); insertClusterMemberInitialData( db, name, serverId ); } } );
false
enterprise_ha_src_test_java_org_neo4j_test_AbstractClusterTest.java
1,608
public abstract class AbstractClusterTest { public @Rule TestName testName = new TestName(); private File dir; protected LifeSupport life = new LifeSupport(); private final Provider provider; protected ClusterManager clusterManager; protected ManagedCluster cluster; protected AbstractClusterTest( ClusterManager.Provider provider ) { this.provider = provider; } protected AbstractClusterTest() { this( clusterOfSize( 3 ) ); } @Before public void before() throws Exception { dir = TargetDirectory.forTest( getClass() ).cleanDirectory( testName.getMethodName() ); clusterManager = life.add( new ClusterManager( provider, dir, stringMap( default_timeout.name(), "1s" ) ) { @Override protected void config( GraphDatabaseBuilder builder, String clusterName, int serverId ) { super.config( builder, clusterName, serverId ); configureClusterMember( builder, clusterName, serverId ); } @Override protected void insertInitialData( GraphDatabaseService db, String name, int serverId ) { super.insertInitialData( db, name, serverId ); insertClusterMemberInitialData( db, name, serverId ); } } ); life.start(); cluster = clusterManager.getDefaultCluster(); cluster.await( masterAvailable() ); } protected void configureClusterMember( GraphDatabaseBuilder builder, String clusterName, int serverId ) { } protected void insertClusterMemberInitialData( GraphDatabaseService db, String name, int serverId ) { } @After public void after() throws Exception { life.shutdown(); } }
false
enterprise_ha_src_test_java_org_neo4j_test_AbstractClusterTest.java
1,609
public class JSONTokener { private int index; private Reader reader; private char lastChar; private boolean useLastChar; /** * Construct a JSONTokener from a string. * * @param reader A reader. */ public JSONTokener(Reader reader) { this.reader = reader.markSupported() ? reader : new BufferedReader(reader); this.useLastChar = false; this.index = 0; } /** * Construct a JSONTokener from a string. * * @param s A source string. */ public JSONTokener(String s) { this(new StringReader(s)); } /** * Back up one character. This provides a sort of lookahead capability, * so that you can test for a digit or letter before attempting to parse * the next number or identifier. */ public void back() throws JSONException { if (useLastChar || index <= 0) { throw new JSONException("Stepping back two steps is not supported"); } index -= 1; useLastChar = true; } /** * Get the hex value of a character (base16). * @param c A character between '0' and '9' or between 'A' and 'F' or * between 'a' and 'f'. * @return An int between 0 and 15, or -1 if c was not a hex digit. */ public static int dehexchar(char c) { if (c >= '0' && c <= '9') { return c - '0'; } if (c >= 'A' && c <= 'F') { return c - ('A' - 10); } if (c >= 'a' && c <= 'f') { return c - ('a' - 10); } return -1; } /** * Determine if the source string still contains characters that next() * can consume. * @return true if not yet at the end of the source. */ public boolean more() throws JSONException { char nextChar = next(); if (nextChar == 0) { return false; } back(); return true; } /** * Get the next character in the source string. * * @return The next character, or 0 if past the end of the source string. */ public char next() throws JSONException { if (this.useLastChar) { this.useLastChar = false; if (this.lastChar != 0) { this.index += 1; } return this.lastChar; } int c; try { c = this.reader.read(); } catch (IOException exc) { throw new JSONException(exc); } if (c <= 0) { // End of stream this.lastChar = 0; return 0; } this.index += 1; this.lastChar = (char) c; return this.lastChar; } /** * Consume the next character, and check that it matches a specified * character. * @param c The character to match. * @return The character. * @throws JSONException if the character does not match. */ public char next(char c) throws JSONException { char n = next(); if (n != c) { throw syntaxError("Expected '" + c + "' and instead saw '" + n + "'"); } return n; } /** * Get the next n characters. * * @param n The number of characters to take. * @return A string of n characters. * @throws JSONException * Substring bounds error if there are not * n characters remaining in the source string. */ public String next(int n) throws JSONException { if (n == 0) { return ""; } char[] buffer = new char[n]; int pos = 0; if (this.useLastChar) { this.useLastChar = false; buffer[0] = this.lastChar; pos = 1; } try { int len; while ((pos < n) && ((len = reader.read(buffer, pos, n - pos)) != -1)) { pos += len; } } catch (IOException exc) { throw new JSONException(exc); } this.index += pos; if (pos < n) { throw syntaxError("Substring bounds error"); } this.lastChar = buffer[n - 1]; return new String(buffer); } /** * Get the next char in the string, skipping whitespace. * @throws JSONException * @return A character, or 0 if there are no more characters. */ public char nextClean() throws JSONException { for (;;) { char c = next(); if (c == 0 || c > ' ') { return c; } } } /** * Return the characters up to the next close quote character. * Backslash processing is done. The formal JSON format does not * allow strings in single quotes, but an implementation is allowed to * accept them. * @param quote The quoting character, either * <code>"</code>&nbsp;<small>(double quote)</small> or * <code>'</code>&nbsp;<small>(single quote)</small>. * @return A String. * @throws JSONException Unterminated string. */ public String nextString(char quote) throws JSONException { char c; StringBuffer sb = new StringBuffer(); for (;;) { c = next(); switch (c) { case 0: case '\n': case '\r': throw syntaxError("Unterminated string"); case '\\': c = next(); switch (c) { case 'b': sb.append('\b'); break; case 't': sb.append('\t'); break; case 'n': sb.append('\n'); break; case 'f': sb.append('\f'); break; case 'r': sb.append('\r'); break; case 'u': sb.append((char)Integer.parseInt(next(4), 16)); break; case '"': case '\'': case '\\': case '/': sb.append(c); break; default: throw syntaxError("Illegal escape."); } break; default: if (c == quote) { return sb.toString(); } sb.append(c); } } } /** * Get the text up but not including the specified character or the * end of line, whichever comes first. * @param d A delimiter character. * @return A string. */ public String nextTo(char d) throws JSONException { StringBuffer sb = new StringBuffer(); for (;;) { char c = next(); if (c == d || c == 0 || c == '\n' || c == '\r') { if (c != 0) { back(); } return sb.toString().trim(); } sb.append(c); } } /** * Get the text up but not including one of the specified delimiter * characters or the end of line, whichever comes first. * @param delimiters A set of delimiter characters. * @return A string, trimmed. */ public String nextTo(String delimiters) throws JSONException { char c; StringBuffer sb = new StringBuffer(); for (;;) { c = next(); if (delimiters.indexOf(c) >= 0 || c == 0 || c == '\n' || c == '\r') { if (c != 0) { back(); } return sb.toString().trim(); } sb.append(c); } } /** * Get the next value. The value can be a Boolean, Double, Integer, * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object. * @throws JSONException If syntax error. * * @return An object. */ public Object nextValue() throws JSONException { char c = nextClean(); String s; switch (c) { case '"': case '\'': return nextString(c); case '{': back(); return new JSONObject(this); case '[': case '(': back(); return new JSONArray(this); } /* * Handle unquoted text. This could be the values true, false, or * null, or it can be a number. An implementation (such as this one) * is allowed to also accept non-standard forms. * * Accumulate characters until we reach the end of the text or a * formatting character. */ StringBuffer sb = new StringBuffer(); while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { sb.append(c); c = next(); } back(); s = sb.toString().trim(); if (s.equals("")) { throw syntaxError("Missing value"); } return JSONObject.stringToValue(s); } /** * Skip characters until the next character is the requested character. * If the requested character is not found, no characters are skipped. * @param to A character to skip to. * @return The requested character, or zero if the requested character * is not found. */ public char skipTo(char to) throws JSONException { char c; try { int startIndex = this.index; reader.mark(Integer.MAX_VALUE); do { c = next(); if (c == 0) { reader.reset(); this.index = startIndex; return c; } } while (c != to); } catch (IOException exc) { throw new JSONException(exc); } back(); return c; } /** * Make a JSONException to signal a syntax error. * * @param message The error message. * @return A JSONException object, suitable for throwing */ public JSONException syntaxError(String message) { return new JSONException(message + toString()); } /** * Make a printable string of this JSONTokener. * * @return " at character [this.index]" */ @Override public String toString() { return " at character " + index; } }
false
community_shell_src_main_java_org_neo4j_shell_util_json_JSONTokener.java
1,610
public class JSONParser { public static Object parse( String json ) throws ShellException { try { final String input = json.trim(); if ( input.isEmpty() ) { return null; } if ( input.charAt( 0 ) == '{' ) { return new JSONObject( input ).toMap(); } if ( input.charAt( 0 ) == '[' ) { return new JSONArray( input ).toList(); } final Object value = JSONObject.stringToValue( input ); if ( value.equals( null ) ) { return null; } return value; } catch ( JSONException e ) { throw new ShellException( "Could not parse value " + json + " " + e.getMessage() ); } } }
false
community_shell_src_main_java_org_neo4j_shell_util_json_JSONParser.java
1,611
private static final class Null { /** * There is only intended to be a single instance of the NULL object, * so the clone method returns itself. * @return NULL. */ @Override protected final Object clone() { return this; } /** * A Null object is equal to the null value and to itself. * @param object An object to test for nullness. * @return true if the object parameter is the JSONObject.NULL object * or null. */ @Override public boolean equals(Object object) { return object == null || object == this; } /** * Get the "null" string value. * @return The string "null". */ @Override public String toString() { return "null"; } }
false
community_shell_src_main_java_org_neo4j_shell_util_json_JSONObject.java
1,612
public class JSONObject { /** * JSONObject.NULL is equivalent to the value that JavaScript calls null, * whilst Java's null is equivalent to the value that JavaScript calls * undefined. */ private static final class Null { /** * There is only intended to be a single instance of the NULL object, * so the clone method returns itself. * @return NULL. */ @Override protected final Object clone() { return this; } /** * A Null object is equal to the null value and to itself. * @param object An object to test for nullness. * @return true if the object parameter is the JSONObject.NULL object * or null. */ @Override public boolean equals(Object object) { return object == null || object == this; } /** * Get the "null" string value. * @return The string "null". */ @Override public String toString() { return "null"; } } /** * The map where the JSONObject's properties are kept. */ private Map map; public Map toMap() { return Collections.unmodifiableMap( map ); } /** * It is sometimes more convenient and less ambiguous to have a * <code>NULL</code> object than to use Java's <code>null</code> value. * <code>JSONObject.NULL.equals(null)</code> returns <code>true</code>. * <code>JSONObject.NULL.toString()</code> returns <code>"null"</code>. */ public static final Object NULL = new Null(); /** * Construct an empty JSONObject. */ public JSONObject() { this.map = new HashMap(); } /** * Construct a JSONObject from a subset of another JSONObject. * An array of strings is used to identify the keys that should be copied. * Missing keys are ignored. * @param jo A JSONObject. * @param names An array of strings. * @exception JSONException If a value is a non-finite number or if a name is duplicated. */ public JSONObject(JSONObject jo, String[] names) throws JSONException { this(); for (int i = 0; i < names.length; i += 1) { putOnce(names[i], jo.opt(names[i])); } } /** * Construct a JSONObject from a JSONTokener. * @param x A JSONTokener object containing the source string. * @throws JSONException If there is a syntax error in the source string * or a duplicated key. */ public JSONObject(JSONTokener x) throws JSONException { this(); char c; String key; if (x.nextClean() != '{') { throw x.syntaxError("A JSONObject text must begin with '{'"); } for (;;) { c = x.nextClean(); switch (c) { case 0: throw x.syntaxError("A JSONObject text must end with '}'"); case '}': return; default: x.back(); key = x.nextValue().toString(); } /* * The key is followed by ':'. We will also tolerate '=' or '=>'. */ c = x.nextClean(); if (c == '=') { if (x.next() != '>') { x.back(); } } else if (c != ':') { throw x.syntaxError("Expected a ':' after a key"); } putOnce(key, x.nextValue()); /* * Pairs are separated by ','. We will also tolerate ';'. */ switch (x.nextClean()) { case ';': case ',': if (x.nextClean() == '}') { return; } x.back(); break; case '}': return; default: throw x.syntaxError("Expected a ',' or '}'"); } } } /** * Construct a JSONObject from a Map. * * @param map A map object that can be used to initialize the contents of * the JSONObject. */ public JSONObject(Map map) { this.map = (map == null) ? new HashMap() : map; } /** * Construct a JSONObject from a Map. * * Note: Use this constructor when the map contains <key,bean>. * * @param map - A map with Key-Bean data. * @param includeSuperClass - Tell whether to include the super class properties. */ public JSONObject(Map map, boolean includeSuperClass) { this.map = new HashMap(); if (map != null) { Iterator i = map.entrySet().iterator(); while (i.hasNext()) { Map.Entry e = (Map.Entry)i.next(); if (isStandardProperty(e.getValue().getClass())) { this.map.put(e.getKey(), e.getValue()); } else { this.map.put(e.getKey(), new JSONObject(e.getValue(), includeSuperClass)); } } } } /** * Construct a JSONObject from an Object using bean getters. * It reflects on all of the public methods of the object. * For each of the methods with no parameters and a name starting * with <code>"get"</code> or <code>"is"</code> followed by an uppercase letter, * the method is invoked, and a key and the value returned from the getter method * are put into the new JSONObject. * * The key is formed by removing the <code>"get"</code> or <code>"is"</code> prefix. * If the second remaining character is not upper case, then the first * character is converted to lower case. * * For example, if an object has a method named <code>"getName"</code>, and * if the result of calling <code>object.getName()</code> is <code>"Larry Fine"</code>, * then the JSONObject will contain <code>"name": "Larry Fine"</code>. * * @param bean An object that has getter methods that should be used * to make a JSONObject. */ public JSONObject(Object bean) { this(); populateInternalMap(bean, false); } /** * Construct a JSONObject from an Object using bean getters. * It reflects on all of the public methods of the object. * For each of the methods with no parameters and a name starting * with <code>"get"</code> or <code>"is"</code> followed by an uppercase letter, * the method is invoked, and a key and the value returned from the getter method * are put into the new JSONObject. * * The key is formed by removing the <code>"get"</code> or <code>"is"</code> prefix. * If the second remaining character is not upper case, then the first * character is converted to lower case. * * @param bean An object that has getter methods that should be used * to make a JSONObject. * @param includeSuperClass If true, include the super class properties. */ public JSONObject(Object bean, boolean includeSuperClass) { this(); populateInternalMap(bean, includeSuperClass); } private void populateInternalMap(Object bean, boolean includeSuperClass){ Class klass = bean.getClass(); /* If klass.getSuperClass is System class then force includeSuperClass to false. */ if (klass.getClassLoader() == null) { includeSuperClass = false; } Method[] methods = (includeSuperClass) ? klass.getMethods() : klass.getDeclaredMethods(); for (int i = 0; i < methods.length; i += 1) { try { Method method = methods[i]; if (Modifier.isPublic(method.getModifiers())) { String name = method.getName(); String key = ""; if (name.startsWith("get")) { key = name.substring(3); } else if (name.startsWith("is")) { key = name.substring(2); } if (key.length() > 0 && Character.isUpperCase(key.charAt(0)) && method.getParameterTypes().length == 0) { if (key.length() == 1) { key = key.toLowerCase(); } else if (!Character.isUpperCase(key.charAt(1))) { key = key.substring(0, 1).toLowerCase() + key.substring(1); } Object result = method.invoke(bean, (Object[])null); if (result == null) { map.put(key, NULL); } else if (result.getClass().isArray()) { map.put(key, new JSONArray(result, includeSuperClass)); } else if (result instanceof Collection) { // List or Set map.put(key, new JSONArray((Collection)result, includeSuperClass)); } else if (result instanceof Map) { map.put(key, new JSONObject((Map)result, includeSuperClass)); } else if (isStandardProperty(result.getClass())) { // Primitives, String and Wrapper map.put(key, result); } else { if (result.getClass().getPackage().getName().startsWith("java") || result.getClass().getClassLoader() == null) { map.put(key, result.toString()); } else { // User defined Objects map.put(key, new JSONObject(result, includeSuperClass)); } } } } } catch (Exception e) { throw new RuntimeException(e); } } } static boolean isStandardProperty(Class clazz) { return clazz.isPrimitive() || clazz.isAssignableFrom(Byte.class) || clazz.isAssignableFrom(Short.class) || clazz.isAssignableFrom(Integer.class) || clazz.isAssignableFrom(Long.class) || clazz.isAssignableFrom(Float.class) || clazz.isAssignableFrom(Double.class) || clazz.isAssignableFrom(Character.class) || clazz.isAssignableFrom(String.class) || clazz.isAssignableFrom(Boolean.class); } /** * Construct a JSONObject from an Object, using reflection to find the * public members. The resulting JSONObject's keys will be the strings * from the names array, and the values will be the field values associated * with those keys in the object. If a key is not found or not visible, * then it will not be copied into the new JSONObject. * @param object An object that has fields that should be used to make a * JSONObject. * @param names An array of strings, the names of the fields to be obtained * from the object. */ public JSONObject(Object object, String names[]) { this(); Class c = object.getClass(); for (int i = 0; i < names.length; i += 1) { String name = names[i]; try { putOpt(name, c.getField(name).get(object)); } catch (Exception e) { /* forget about it */ } } } /** * Construct a JSONObject from a source JSON text string. * This is the most commonly used JSONObject constructor. * @param source A string beginning * with <code>{</code>&nbsp;<small>(left brace)</small> and ending * with <code>}</code>&nbsp;<small>(right brace)</small>. * @exception JSONException If there is a syntax error in the source * string or a duplicated key. */ public JSONObject(String source) throws JSONException { this(new JSONTokener(source)); } /** * Accumulate values under a key. It is similar to the put method except * that if there is already an object stored under the key then a * JSONArray is stored under the key to hold all of the accumulated values. * If there is already a JSONArray, then the new value is appended to it. * In contrast, the put method replaces the previous value. * @param key A key string. * @param value An object to be accumulated under the key. * @return this. * @throws JSONException If the value is an invalid number * or if the key is null. */ public JSONObject accumulate(String key, Object value) throws JSONException { testValidity(value); Object o = opt(key); if (o == null) { put(key, value instanceof JSONArray ? new JSONArray().put(value) : value); } else if (o instanceof JSONArray) { ((JSONArray)o).put(value); } else { put(key, new JSONArray().put(o).put(value)); } return this; } /** * Append values to the array under a key. If the key does not exist in the * JSONObject, then the key is put in the JSONObject with its value being a * JSONArray containing the value parameter. If the key was already * associated with a JSONArray, then the value parameter is appended to it. * @param key A key string. * @param value An object to be accumulated under the key. * @return this. * @throws JSONException If the key is null or if the current value * associated with the key is not a JSONArray. */ public JSONObject append(String key, Object value) throws JSONException { testValidity(value); Object o = opt(key); if (o == null) { put(key, new JSONArray().put(value)); } else if (o instanceof JSONArray) { put(key, ((JSONArray)o).put(value)); } else { throw new JSONException("JSONObject[" + key + "] is not a JSONArray."); } return this; } /** * Produce a string from a double. The string "null" will be returned if * the number is not finite. * @param d A double. * @return A String. */ static public String doubleToString(double d) { if (Double.isInfinite(d) || Double.isNaN(d)) { return "null"; } // Shave off trailing zeros and decimal point, if possible. String s = Double.toString(d); if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) { while (s.endsWith("0")) { s = s.substring(0, s.length() - 1); } if (s.endsWith(".")) { s = s.substring(0, s.length() - 1); } } return s; } /** * Get the value object associated with a key. * * @param key A key string. * @return The object associated with the key. * @throws JSONException if the key is not found. */ public Object get(String key) throws JSONException { Object o = opt(key); if (o == null) { throw new JSONException("JSONObject[" + quote(key) + "] not found."); } return o; } /** * Get the boolean value associated with a key. * * @param key A key string. * @return The truth. * @throws JSONException * if the value is not a Boolean or the String "true" or "false". */ public boolean getBoolean(String key) throws JSONException { Object o = get(key); if (o.equals(Boolean.FALSE) || (o instanceof String && ((String)o).equalsIgnoreCase("false"))) { return false; } else if (o.equals(Boolean.TRUE) || (o instanceof String && ((String)o).equalsIgnoreCase("true"))) { return true; } throw new JSONException("JSONObject[" + quote(key) + "] is not a Boolean."); } /** * Get the double value associated with a key. * @param key A key string. * @return The numeric value. * @throws JSONException if the key is not found or * if the value is not a Number object and cannot be converted to a number. */ public double getDouble(String key) throws JSONException { Object o = get(key); try { return o instanceof Number ? ((Number)o).doubleValue() : Double.valueOf((String)o).doubleValue(); } catch (Exception e) { throw new JSONException("JSONObject[" + quote(key) + "] is not a number."); } } /** * Get the int value associated with a key. If the number value is too * large for an int, it will be clipped. * * @param key A key string. * @return The integer value. * @throws JSONException if the key is not found or if the value cannot * be converted to an integer. */ public int getInt(String key) throws JSONException { Object o = get(key); return o instanceof Number ? ((Number)o).intValue() : (int)getDouble(key); } /** * Get the JSONArray value associated with a key. * * @param key A key string. * @return A JSONArray which is the value. * @throws JSONException if the key is not found or * if the value is not a JSONArray. */ public JSONArray getJSONArray(String key) throws JSONException { Object o = get(key); if (o instanceof JSONArray) { return (JSONArray)o; } throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONArray."); } /** * Get the JSONObject value associated with a key. * * @param key A key string. * @return A JSONObject which is the value. * @throws JSONException if the key is not found or * if the value is not a JSONObject. */ public JSONObject getJSONObject(String key) throws JSONException { Object o = get(key); if (o instanceof JSONObject) { return (JSONObject)o; } throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONObject."); } /** * Get the long value associated with a key. If the number value is too * long for a long, it will be clipped. * * @param key A key string. * @return The long value. * @throws JSONException if the key is not found or if the value cannot * be converted to a long. */ public long getLong(String key) throws JSONException { Object o = get(key); return o instanceof Number ? ((Number)o).longValue() : (long)getDouble(key); } /** * Get an array of field names from a JSONObject. * * @return An array of field names, or null if there are no names. */ public static String[] getNames(JSONObject jo) { int length = jo.length(); if (length == 0) { return null; } Iterator i = jo.keys(); String[] names = new String[length]; int j = 0; while (i.hasNext()) { names[j] = (String)i.next(); j += 1; } return names; } /** * Get an array of field names from an Object. * * @return An array of field names, or null if there are no names. */ public static String[] getNames(Object object) { if (object == null) { return null; } Class klass = object.getClass(); Field[] fields = klass.getFields(); int length = fields.length; if (length == 0) { return null; } String[] names = new String[length]; for (int i = 0; i < length; i += 1) { names[i] = fields[i].getName(); } return names; } /** * Get the string associated with a key. * * @param key A key string. * @return A string which is the value. * @throws JSONException if the key is not found. */ public String getString(String key) throws JSONException { return get(key).toString(); } /** * Determine if the JSONObject contains a specific key. * @param key A key string. * @return true if the key exists in the JSONObject. */ public boolean has(String key) { return this.map.containsKey(key); } /** * Determine if the value associated with the key is null or if there is * no value. * @param key A key string. * @return true if there is no value associated with the key or if * the value is the JSONObject.NULL object. */ public boolean isNull(String key) { return JSONObject.NULL.equals(opt(key)); } /** * Get an enumeration of the keys of the JSONObject. * * @return An iterator of the keys. */ public Iterator keys() { return this.map.keySet().iterator(); } /** * Get the number of keys stored in the JSONObject. * * @return The number of keys in the JSONObject. */ public int length() { return this.map.size(); } /** * Produce a JSONArray containing the names of the elements of this * JSONObject. * @return A JSONArray containing the key strings, or null if the JSONObject * is empty. */ public JSONArray names() { JSONArray ja = new JSONArray(); Iterator keys = keys(); while (keys.hasNext()) { ja.put(keys.next()); } return ja.length() == 0 ? null : ja; } /** * Produce a string from a Number. * @param n A Number * @return A String. * @throws JSONException If n is a non-finite number. */ static public String numberToString(Number n) throws JSONException { if (n == null) { throw new JSONException("Null pointer"); } testValidity(n); // Shave off trailing zeros and decimal point, if possible. String s = n.toString(); if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) { while (s.endsWith("0")) { s = s.substring(0, s.length() - 1); } if (s.endsWith(".")) { s = s.substring(0, s.length() - 1); } } return s; } /** * Get an optional value associated with a key. * @param key A key string. * @return An object which is the value, or null if there is no value. */ public Object opt(String key) { return key == null ? null : this.map.get(key); } /** * Get an optional boolean associated with a key. * It returns false if there is no such key, or if the value is not * Boolean.TRUE or the String "true". * * @param key A key string. * @return The truth. */ public boolean optBoolean(String key) { return optBoolean(key, false); } /** * Get an optional boolean associated with a key. * It returns the defaultValue if there is no such key, or if it is not * a Boolean or the String "true" or "false" (case insensitive). * * @param key A key string. * @param defaultValue The default. * @return The truth. */ public boolean optBoolean(String key, boolean defaultValue) { try { return getBoolean(key); } catch (Exception e) { return defaultValue; } } /** * Put a key/value pair in the JSONObject, where the value will be a * JSONArray which is produced from a Collection. * @param key A key string. * @param value A Collection value. * @return this. * @throws JSONException */ public JSONObject put(String key, Collection value) throws JSONException { put(key, new JSONArray(value)); return this; } /** * Get an optional double associated with a key, * or NaN if there is no such key or if its value is not a number. * If the value is a string, an attempt will be made to evaluate it as * a number. * * @param key A string which is the key. * @return An object which is the value. */ public double optDouble(String key) { return optDouble(key, Double.NaN); } /** * Get an optional double associated with a key, or the * defaultValue if there is no such key or if its value is not a number. * If the value is a string, an attempt will be made to evaluate it as * a number. * * @param key A key string. * @param defaultValue The default. * @return An object which is the value. */ public double optDouble(String key, double defaultValue) { try { Object o = opt(key); return o instanceof Number ? ((Number)o).doubleValue() : new Double((String)o).doubleValue(); } catch (Exception e) { return defaultValue; } } /** * Get an optional int value associated with a key, * or zero if there is no such key or if the value is not a number. * If the value is a string, an attempt will be made to evaluate it as * a number. * * @param key A key string. * @return An object which is the value. */ public int optInt(String key) { return optInt(key, 0); } /** * Get an optional int value associated with a key, * or the default if there is no such key or if the value is not a number. * If the value is a string, an attempt will be made to evaluate it as * a number. * * @param key A key string. * @param defaultValue The default. * @return An object which is the value. */ public int optInt(String key, int defaultValue) { try { return getInt(key); } catch (Exception e) { return defaultValue; } } /** * Get an optional JSONArray associated with a key. * It returns null if there is no such key, or if its value is not a * JSONArray. * * @param key A key string. * @return A JSONArray which is the value. */ public JSONArray optJSONArray(String key) { Object o = opt(key); return o instanceof JSONArray ? (JSONArray)o : null; } /** * Get an optional JSONObject associated with a key. * It returns null if there is no such key, or if its value is not a * JSONObject. * * @param key A key string. * @return A JSONObject which is the value. */ public JSONObject optJSONObject(String key) { Object o = opt(key); return o instanceof JSONObject ? (JSONObject)o : null; } /** * Get an optional long value associated with a key, * or zero if there is no such key or if the value is not a number. * If the value is a string, an attempt will be made to evaluate it as * a number. * * @param key A key string. * @return An object which is the value. */ public long optLong(String key) { return optLong(key, 0); } /** * Get an optional long value associated with a key, * or the default if there is no such key or if the value is not a number. * If the value is a string, an attempt will be made to evaluate it as * a number. * * @param key A key string. * @param defaultValue The default. * @return An object which is the value. */ public long optLong(String key, long defaultValue) { try { return getLong(key); } catch (Exception e) { return defaultValue; } } /** * Get an optional string associated with a key. * It returns an empty string if there is no such key. If the value is not * a string and is not null, then it is coverted to a string. * * @param key A key string. * @return A string which is the value. */ public String optString(String key) { return optString(key, ""); } /** * Get an optional string associated with a key. * It returns the defaultValue if there is no such key. * * @param key A key string. * @param defaultValue The default. * @return A string which is the value. */ public String optString(String key, String defaultValue) { Object o = opt(key); return o != null ? o.toString() : defaultValue; } /** * Put a key/boolean pair in the JSONObject. * * @param key A key string. * @param value A boolean which is the value. * @return this. * @throws JSONException If the key is null. */ public JSONObject put(String key, boolean value) throws JSONException { put(key, value ? Boolean.TRUE : Boolean.FALSE); return this; } /** * Put a key/double pair in the JSONObject. * * @param key A key string. * @param value A double which is the value. * @return this. * @throws JSONException If the key is null or if the number is invalid. */ public JSONObject put(String key, double value) throws JSONException { put(key, new Double(value)); return this; } /** * Put a key/int pair in the JSONObject. * * @param key A key string. * @param value An int which is the value. * @return this. * @throws JSONException If the key is null. */ public JSONObject put(String key, int value) throws JSONException { put(key, new Integer(value)); return this; } /** * Put a key/long pair in the JSONObject. * * @param key A key string. * @param value A long which is the value. * @return this. * @throws JSONException If the key is null. */ public JSONObject put(String key, long value) throws JSONException { put(key, new Long(value)); return this; } /** * Put a key/value pair in the JSONObject, where the value will be a * JSONObject which is produced from a Map. * @param key A key string. * @param value A Map value. * @return this. * @throws JSONException */ public JSONObject put(String key, Map value) throws JSONException { put(key, new JSONObject(value)); return this; } /** * Put a key/value pair in the JSONObject. If the value is null, * then the key will be removed from the JSONObject if it is present. * @param key A key string. * @param value An object which is the value. It should be of one of these * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, * or the JSONObject.NULL object. * @return this. * @throws JSONException If the value is non-finite number * or if the key is null. */ public JSONObject put(String key, Object value) throws JSONException { if (key == null) { throw new JSONException("Null key."); } if (value != null) { testValidity(value); this.map.put(key, value); } else { remove(key); } return this; } /** * Put a key/value pair in the JSONObject, but only if the key and the * value are both non-null, and only if there is not already a member * with that name. * @param key * @param value * @return his. * @throws JSONException if the key is a duplicate */ public JSONObject putOnce(String key, Object value) throws JSONException { if (key != null && value != null) { if (opt(key) != null) { throw new JSONException("Duplicate key \"" + key + "\""); } put(key, value); } return this; } /** * Put a key/value pair in the JSONObject, but only if the * key and the value are both non-null. * @param key A key string. * @param value An object which is the value. It should be of one of these * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, * or the JSONObject.NULL object. * @return this. * @throws JSONException If the value is a non-finite number. */ public JSONObject putOpt(String key, Object value) throws JSONException { if (key != null && value != null) { put(key, value); } return this; } /** * Produce a string in double quotes with backslash sequences in all the * right places. A backslash will be inserted within </, allowing JSON * text to be delivered in HTML. In JSON text, a string cannot contain a * control character or an unescaped quote or backslash. * @param string A String * @return A String correctly formatted for insertion in a JSON text. */ public static String quote(String string) { if (string == null || string.length() == 0) { return "\"\""; } char b; char c = 0; int i; int len = string.length(); StringBuffer sb = new StringBuffer(len + 4); String t; sb.append('"'); for (i = 0; i < len; i += 1) { b = c; c = string.charAt(i); switch (c) { case '\\': case '"': sb.append('\\'); sb.append(c); break; case '/': if (b == '<') { sb.append('\\'); } sb.append(c); break; case '\b': sb.append("\\b"); break; case '\t': sb.append("\\t"); break; case '\n': sb.append("\\n"); break; case '\f': sb.append("\\f"); break; case '\r': sb.append("\\r"); break; default: if (c < ' ' || (c >= '\u0080' && c < '\u00a0') || (c >= '\u2000' && c < '\u2100')) { t = "000" + Integer.toHexString(c); sb.append("\\u" + t.substring(t.length() - 4)); } else { sb.append(c); } } } sb.append('"'); return sb.toString(); } /** * Remove a name and its value, if present. * @param key The name to be removed. * @return The value that was associated with the name, * or null if there was no value. */ public Object remove(String key) { return this.map.remove(key); } /** * Get an enumeration of the keys of the JSONObject. * The keys will be sorted alphabetically. * * @return An iterator of the keys. */ public Iterator sortedKeys() { return new TreeSet(this.map.keySet()).iterator(); } /** * Try to convert a string into a number, boolean, or null. If the string * can't be converted, return the string. * @param s A String. * @return A simple JSON value. */ static public Object stringToValue(String s) { if (s.equals("")) { return s; } if (s.equalsIgnoreCase("true")) { return Boolean.TRUE; } if (s.equalsIgnoreCase("false")) { return Boolean.FALSE; } if (s.equalsIgnoreCase("null")) { return JSONObject.NULL; } /* * If it might be a number, try converting it. We support the 0- and 0x- * conventions. If a number cannot be produced, then the value will just * be a string. Note that the 0-, 0x-, plus, and implied string * conventions are non-standard. A JSON parser is free to accept * non-JSON forms as long as it accepts all correct JSON forms. */ char b = s.charAt(0); if ((b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+') { if (b == '0') { if (s.length() > 2 && (s.charAt(1) == 'x' || s.charAt(1) == 'X')) { try { return new Integer(Integer.parseInt(s.substring(2), 16)); } catch (Exception e) { /* Ignore the error */ } } else { try { return new Integer(Integer.parseInt(s, 8)); } catch (Exception e) { /* Ignore the error */ } } } try { if (s.indexOf('.') > -1 || s.indexOf('e') > -1 || s.indexOf('E') > -1) { return Double.valueOf(s); } else { Long myLong = new Long(s); if (myLong.longValue() == myLong.intValue()) { return new Integer(myLong.intValue()); } else { return myLong; } } } catch (Exception f) { /* Ignore the error */ } } return s; } /** * Throw an exception if the object is an NaN or infinite number. * @param o The object to test. * @throws JSONException If o is a non-finite number. */ static void testValidity(Object o) throws JSONException { if (o != null) { if (o instanceof Double) { if (((Double)o).isInfinite() || ((Double)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } else if (o instanceof Float) { if (((Float)o).isInfinite() || ((Float)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } } } /** * Produce a JSONArray containing the values of the members of this * JSONObject. * @param names A JSONArray containing a list of key strings. This * determines the sequence of the values in the result. * @return A JSONArray of values. * @throws JSONException If any of the values are non-finite numbers. */ public JSONArray toJSONArray(JSONArray names) throws JSONException { if (names == null || names.length() == 0) { return null; } JSONArray ja = new JSONArray(); for (int i = 0; i < names.length(); i += 1) { ja.put(this.opt(names.getString(i))); } return ja; } /** * Make a JSON text of this JSONObject. For compactness, no whitespace * is added. If this would not result in a syntactically correct JSON text, * then null will be returned instead. * <p> * Warning: This method assumes that the data structure is acyclical. * * @return a printable, displayable, portable, transmittable * representation of the object, beginning * with <code>{</code>&nbsp;<small>(left brace)</small> and ending * with <code>}</code>&nbsp;<small>(right brace)</small>. */ @Override public String toString() { try { Iterator keys = keys(); StringBuffer sb = new StringBuffer("{"); while (keys.hasNext()) { if (sb.length() > 1) { sb.append(','); } Object o = keys.next(); sb.append(quote(o.toString())); sb.append(':'); sb.append(valueToString(this.map.get(o))); } sb.append('}'); return sb.toString(); } catch (Exception e) { return null; } } /** * Make a prettyprinted JSON text of this JSONObject. * <p> * Warning: This method assumes that the data structure is acyclical. * @param indentFactor The number of spaces to add to each level of * indentation. * @return a printable, displayable, portable, transmittable * representation of the object, beginning * with <code>{</code>&nbsp;<small>(left brace)</small> and ending * with <code>}</code>&nbsp;<small>(right brace)</small>. * @throws JSONException If the object contains an invalid number. */ public String toString(int indentFactor) throws JSONException { return toString(indentFactor, 0); } /** * Make a prettyprinted JSON text of this JSONObject. * <p> * Warning: This method assumes that the data structure is acyclical. * @param indentFactor The number of spaces to add to each level of * indentation. * @param indent The indentation of the top level. * @return a printable, displayable, transmittable * representation of the object, beginning * with <code>{</code>&nbsp;<small>(left brace)</small> and ending * with <code>}</code>&nbsp;<small>(right brace)</small>. * @throws JSONException If the object contains an invalid number. */ String toString(int indentFactor, int indent) throws JSONException { int j; int n = length(); if (n == 0) { return "{}"; } Iterator keys = sortedKeys(); StringBuffer sb = new StringBuffer("{"); int newindent = indent + indentFactor; Object o; if (n == 1) { o = keys.next(); sb.append(quote(o.toString())); sb.append(": "); sb.append(valueToString(this.map.get(o), indentFactor, indent)); } else { while (keys.hasNext()) { o = keys.next(); if (sb.length() > 1) { sb.append(",\n"); } else { sb.append('\n'); } for (j = 0; j < newindent; j += 1) { sb.append(' '); } sb.append(quote(o.toString())); sb.append(": "); sb.append(valueToString(this.map.get(o), indentFactor, newindent)); } if (sb.length() > 1) { sb.append('\n'); for (j = 0; j < indent; j += 1) { sb.append(' '); } } } sb.append('}'); return sb.toString(); } /** * Make a JSON text of an Object value. If the object has an * value.toJSONString() method, then that method will be used to produce * the JSON text. The method is required to produce a strictly * conforming text. If the object does not contain a toJSONString * method (which is the most common case), then a text will be * produced by other means. If the value is an array or Collection, * then a JSONArray will be made from it and its toJSONString method * will be called. If the value is a MAP, then a JSONObject will be made * from it and its toJSONString method will be called. Otherwise, the * value's toString method will be called, and the result will be quoted. * * <p> * Warning: This method assumes that the data structure is acyclical. * @param value The value to be serialized. * @return a printable, displayable, transmittable * representation of the object, beginning * with <code>{</code>&nbsp;<small>(left brace)</small> and ending * with <code>}</code>&nbsp;<small>(right brace)</small>. * @throws JSONException If the value is or contains an invalid number. */ public static String valueToString(Object value) throws JSONException { if (value == null || value.equals(null)) { return "null"; } if (value instanceof JSONString) { Object o; try { o = ((JSONString)value).toJSONString(); } catch (Exception e) { throw new JSONException(e); } if (o instanceof String) { return (String)o; } throw new JSONException("Bad value from toJSONString: " + o); } if (value instanceof Number) { return numberToString((Number) value); } if (value instanceof Boolean || value instanceof JSONObject || value instanceof JSONArray) { return value.toString(); } if (value instanceof Map) { return new JSONObject((Map)value).toString(); } if (value instanceof Collection) { return new JSONArray((Collection)value).toString(); } if (value.getClass().isArray()) { return new JSONArray(value).toString(); } return quote(value.toString()); } /** * Make a prettyprinted JSON text of an object value. * <p> * Warning: This method assumes that the data structure is acyclical. * @param value The value to be serialized. * @param indentFactor The number of spaces to add to each level of * indentation. * @param indent The indentation of the top level. * @return a printable, displayable, transmittable * representation of the object, beginning * with <code>{</code>&nbsp;<small>(left brace)</small> and ending * with <code>}</code>&nbsp;<small>(right brace)</small>. * @throws JSONException If the object contains an invalid number. */ static String valueToString(Object value, int indentFactor, int indent) throws JSONException { if (value == null || value.equals(null)) { return "null"; } try { if (value instanceof JSONString) { Object o = ((JSONString)value).toJSONString(); if (o instanceof String) { return (String)o; } } } catch (Exception e) { /* forget about it */ } if (value instanceof Number) { return numberToString((Number) value); } if (value instanceof Boolean) { return value.toString(); } if (value instanceof JSONObject) { return ((JSONObject)value).toString(indentFactor, indent); } if (value instanceof JSONArray) { return ((JSONArray)value).toString(indentFactor, indent); } if (value instanceof Map) { return new JSONObject((Map)value).toString(indentFactor, indent); } if (value instanceof Collection) { return new JSONArray((Collection)value).toString(indentFactor, indent); } if (value.getClass().isArray()) { return new JSONArray(value).toString(indentFactor, indent); } return quote(value.toString()); } /** * Write the contents of the JSONObject as JSON text to a writer. * For compactness, no whitespace is added. * <p> * Warning: This method assumes that the data structure is acyclical. * * @return The writer. * @throws JSONException */ public Writer write(Writer writer) throws JSONException { try { boolean b = false; Iterator keys = keys(); writer.write('{'); while (keys.hasNext()) { if (b) { writer.write(','); } Object k = keys.next(); writer.write(quote(k.toString())); writer.write(':'); Object v = this.map.get(k); if (v instanceof JSONObject) { ((JSONObject)v).write(writer); } else if (v instanceof JSONArray) { ((JSONArray)v).write(writer); } else { writer.write(valueToString(v)); } b = true; } writer.write('}'); return writer; } catch (IOException e) { throw new JSONException(e); } } }
false
community_shell_src_main_java_org_neo4j_shell_util_json_JSONObject.java
1,613
public class JSONException extends Exception { private Throwable cause; /** * Constructs a JSONException with an explanatory message. * @param message Detail about the reason for the exception. */ public JSONException(String message) { super(message); } public JSONException(Throwable t) { super(t.getMessage()); this.cause = t; } @Override public Throwable getCause() { return this.cause; } }
false
community_shell_src_main_java_org_neo4j_shell_util_json_JSONException.java
1,614
public class JSONArray { /** * The arrayList where the JSONArray's properties are kept. */ private ArrayList<Object> myArrayList; /** * Construct an empty JSONArray. */ public JSONArray() { this.myArrayList = new ArrayList<Object>(); } public List<Object> toList() { return Collections.unmodifiableList( myArrayList ); } /** * Construct a JSONArray from a JSONTokener. * @param x A JSONTokener * @throws JSONException If there is a syntax error. */ public JSONArray(JSONTokener x) throws JSONException { this(); char c = x.nextClean(); char q; if (c == '[') { q = ']'; } else if (c == '(') { q = ')'; } else { throw x.syntaxError("A JSONArray text must start with '['"); } if (x.nextClean() == ']') { return; } x.back(); for (;;) { if (x.nextClean() == ',') { x.back(); this.myArrayList.add(null); } else { x.back(); this.myArrayList.add(x.nextValue()); } c = x.nextClean(); switch (c) { case ';': case ',': if (x.nextClean() == ']') { return; } x.back(); break; case ']': case ')': if (q != c) { throw x.syntaxError("Expected a '" + new Character(q) + "'"); } return; default: throw x.syntaxError("Expected a ',' or ']'"); } } } /** * Construct a JSONArray from a source JSON text. * @param source A string that begins with * <code>[</code>&nbsp;<small>(left bracket)</small> * and ends with <code>]</code>&nbsp;<small>(right bracket)</small>. * @throws JSONException If there is a syntax error. */ public JSONArray(String source) throws JSONException { this(new JSONTokener(source)); } /** * Construct a JSONArray from a Collection. * @param collection A Collection. */ public JSONArray(Collection collection) { this.myArrayList = (collection == null) ? new ArrayList() : new ArrayList(collection); } /** * Construct a JSONArray from a collection of beans. * The collection should have Java Beans. * * @throws JSONException If not an array. */ public JSONArray(Collection collection, boolean includeSuperClass) { this.myArrayList = new ArrayList<Object>(); if (collection != null) { Iterator iter = collection.iterator();; while (iter.hasNext()) { Object o = iter.next(); if (o instanceof Map) { this.myArrayList.add(new JSONObject((Map)o, includeSuperClass)); } else if (!JSONObject.isStandardProperty(o.getClass())) { this.myArrayList.add(new JSONObject(o, includeSuperClass)); } else { this.myArrayList.add(o); } } } } /** * Construct a JSONArray from an array * @throws JSONException If not an array. */ public JSONArray(Object array) throws JSONException { this(); if (array.getClass().isArray()) { int length = Array.getLength(array); for (int i = 0; i < length; i += 1) { this.put(Array.get(array, i)); } } else { throw new JSONException("JSONArray initial value should be a string or collection or array."); } } /** * Construct a JSONArray from an array with a bean. * The array should have Java Beans. * * @throws JSONException If not an array. */ public JSONArray(Object array,boolean includeSuperClass) throws JSONException { this(); if (array.getClass().isArray()) { int length = Array.getLength(array); for (int i = 0; i < length; i += 1) { Object o = Array.get(array, i); if (JSONObject.isStandardProperty(o.getClass())) { this.myArrayList.add(o); } else { this.myArrayList.add(new JSONObject(o,includeSuperClass)); } } } else { throw new JSONException("JSONArray initial value should be a string or collection or array."); } } /** * Get the object value associated with an index. * @param index * The index must be between 0 and length() - 1. * @return An object value. * @throws JSONException If there is no value for the index. */ public Object get(int index) throws JSONException { Object o = opt(index); if (o == null) { throw new JSONException("JSONArray[" + index + "] not found."); } return o; } /** * Get the boolean value associated with an index. * The string values "true" and "false" are converted to boolean. * * @param index The index must be between 0 and length() - 1. * @return The truth. * @throws JSONException If there is no value for the index or if the * value is not convertable to boolean. */ public boolean getBoolean(int index) throws JSONException { Object o = get(index); if (o.equals(Boolean.FALSE) || (o instanceof String && ((String)o).equalsIgnoreCase("false"))) { return false; } else if (o.equals(Boolean.TRUE) || (o instanceof String && ((String)o).equalsIgnoreCase("true"))) { return true; } throw new JSONException("JSONArray[" + index + "] is not a Boolean."); } /** * Get the double value associated with an index. * * @param index The index must be between 0 and length() - 1. * @return The value. * @throws JSONException If the key is not found or if the value cannot * be converted to a number. */ public double getDouble(int index) throws JSONException { Object o = get(index); try { return o instanceof Number ? ((Number)o).doubleValue() : Double.valueOf((String)o).doubleValue(); } catch (Exception e) { throw new JSONException("JSONArray[" + index + "] is not a number."); } } /** * Get the int value associated with an index. * * @param index The index must be between 0 and length() - 1. * @return The value. * @throws JSONException If the key is not found or if the value cannot * be converted to a number. * if the value cannot be converted to a number. */ public int getInt(int index) throws JSONException { Object o = get(index); return o instanceof Number ? ((Number)o).intValue() : (int)getDouble(index); } /** * Get the JSONArray associated with an index. * @param index The index must be between 0 and length() - 1. * @return A JSONArray value. * @throws JSONException If there is no value for the index. or if the * value is not a JSONArray */ public JSONArray getJSONArray(int index) throws JSONException { Object o = get(index); if (o instanceof JSONArray) { return (JSONArray)o; } throw new JSONException("JSONArray[" + index + "] is not a JSONArray."); } /** * Get the JSONObject associated with an index. * @param index subscript * @return A JSONObject value. * @throws JSONException If there is no value for the index or if the * value is not a JSONObject */ public JSONObject getJSONObject(int index) throws JSONException { Object o = get(index); if (o instanceof JSONObject) { return (JSONObject)o; } throw new JSONException("JSONArray[" + index + "] is not a JSONObject."); } /** * Get the long value associated with an index. * * @param index The index must be between 0 and length() - 1. * @return The value. * @throws JSONException If the key is not found or if the value cannot * be converted to a number. */ public long getLong(int index) throws JSONException { Object o = get(index); return o instanceof Number ? ((Number)o).longValue() : (long)getDouble(index); } /** * Get the string associated with an index. * @param index The index must be between 0 and length() - 1. * @return A string value. * @throws JSONException If there is no value for the index. */ public String getString(int index) throws JSONException { return get(index).toString(); } /** * Determine if the value is null. * @param index The index must be between 0 and length() - 1. * @return true if the value at the index is null, or if there is no value. */ public boolean isNull(int index) { return JSONObject.NULL.equals(opt(index)); } /** * Make a string from the contents of this JSONArray. The * <code>separator</code> string is inserted between each element. * Warning: This method assumes that the data structure is acyclical. * @param separator A string that will be inserted between the elements. * @return a string. * @throws JSONException If the array contains an invalid number. */ public String join(String separator) throws JSONException { int len = length(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < len; i += 1) { if (i > 0) { sb.append(separator); } sb.append(JSONObject.valueToString(this.myArrayList.get(i))); } return sb.toString(); } /** * Get the number of elements in the JSONArray, included nulls. * * @return The length (or size). */ public int length() { return this.myArrayList.size(); } /** * Get the optional object value associated with an index. * @param index The index must be between 0 and length() - 1. * @return An object value, or null if there is no * object at that index. */ public Object opt(int index) { return (index < 0 || index >= length()) ? null : this.myArrayList.get(index); } /** * Get the optional boolean value associated with an index. * It returns false if there is no value at that index, * or if the value is not Boolean.TRUE or the String "true". * * @param index The index must be between 0 and length() - 1. * @return The truth. */ public boolean optBoolean(int index) { return optBoolean(index, false); } /** * Get the optional boolean value associated with an index. * It returns the defaultValue if there is no value at that index or if * it is not a Boolean or the String "true" or "false" (case insensitive). * * @param index The index must be between 0 and length() - 1. * @param defaultValue A boolean default. * @return The truth. */ public boolean optBoolean(int index, boolean defaultValue) { try { return getBoolean(index); } catch (Exception e) { return defaultValue; } } /** * Get the optional double value associated with an index. * NaN is returned if there is no value for the index, * or if the value is not a number and cannot be converted to a number. * * @param index The index must be between 0 and length() - 1. * @return The value. */ public double optDouble(int index) { return optDouble(index, Double.NaN); } /** * Get the optional double value associated with an index. * The defaultValue is returned if there is no value for the index, * or if the value is not a number and cannot be converted to a number. * * @param index subscript * @param defaultValue The default value. * @return The value. */ public double optDouble(int index, double defaultValue) { try { return getDouble(index); } catch (Exception e) { return defaultValue; } } /** * Get the optional int value associated with an index. * Zero is returned if there is no value for the index, * or if the value is not a number and cannot be converted to a number. * * @param index The index must be between 0 and length() - 1. * @return The value. */ public int optInt(int index) { return optInt(index, 0); } /** * Get the optional int value associated with an index. * The defaultValue is returned if there is no value for the index, * or if the value is not a number and cannot be converted to a number. * @param index The index must be between 0 and length() - 1. * @param defaultValue The default value. * @return The value. */ public int optInt(int index, int defaultValue) { try { return getInt(index); } catch (Exception e) { return defaultValue; } } /** * Get the optional JSONArray associated with an index. * @param index subscript * @return A JSONArray value, or null if the index has no value, * or if the value is not a JSONArray. */ public JSONArray optJSONArray(int index) { Object o = opt(index); return o instanceof JSONArray ? (JSONArray)o : null; } /** * Get the optional JSONObject associated with an index. * Null is returned if the key is not found, or null if the index has * no value, or if the value is not a JSONObject. * * @param index The index must be between 0 and length() - 1. * @return A JSONObject value. */ public JSONObject optJSONObject(int index) { Object o = opt(index); return o instanceof JSONObject ? (JSONObject)o : null; } /** * Get the optional long value associated with an index. * Zero is returned if there is no value for the index, * or if the value is not a number and cannot be converted to a number. * * @param index The index must be between 0 and length() - 1. * @return The value. */ public long optLong(int index) { return optLong(index, 0); } /** * Get the optional long value associated with an index. * The defaultValue is returned if there is no value for the index, * or if the value is not a number and cannot be converted to a number. * @param index The index must be between 0 and length() - 1. * @param defaultValue The default value. * @return The value. */ public long optLong(int index, long defaultValue) { try { return getLong(index); } catch (Exception e) { return defaultValue; } } /** * Get the optional string value associated with an index. It returns an * empty string if there is no value at that index. If the value * is not a string and is not null, then it is coverted to a string. * * @param index The index must be between 0 and length() - 1. * @return A String value. */ public String optString(int index) { return optString(index, ""); } /** * Get the optional string associated with an index. * The defaultValue is returned if the key is not found. * * @param index The index must be between 0 and length() - 1. * @param defaultValue The default value. * @return A String value. */ public String optString(int index, String defaultValue) { Object o = opt(index); return o != null ? o.toString() : defaultValue; } /** * Append a boolean value. This increases the array's length by one. * * @param value A boolean value. * @return this. */ public JSONArray put(boolean value) { put(value ? Boolean.TRUE : Boolean.FALSE); return this; } /** * Put a value in the JSONArray, where the value will be a * JSONArray which is produced from a Collection. * @param value A Collection value. * @return this. */ public JSONArray put(Collection value) { put(new JSONArray(value)); return this; } /** * Append a double value. This increases the array's length by one. * * @param value A double value. * @throws JSONException if the value is not finite. * @return this. */ public JSONArray put(double value) throws JSONException { Double d = new Double(value); JSONObject.testValidity(d); put(d); return this; } /** * Append an int value. This increases the array's length by one. * * @param value An int value. * @return this. */ public JSONArray put(int value) { put(new Integer(value)); return this; } /** * Append an long value. This increases the array's length by one. * * @param value A long value. * @return this. */ public JSONArray put(long value) { put(new Long(value)); return this; } /** * Put a value in the JSONArray, where the value will be a * JSONObject which is produced from a Map. * @param value A Map value. * @return this. */ public JSONArray put(Map value) { put(new JSONObject(value)); return this; } /** * Append an object value. This increases the array's length by one. * @param value An object value. The value should be a * Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the * JSONObject.NULL object. * @return this. */ public JSONArray put(Object value) { this.myArrayList.add(value); return this; } /** * Put or replace a boolean value in the JSONArray. If the index is greater * than the length of the JSONArray, then null elements will be added as * necessary to pad it out. * @param index The subscript. * @param value A boolean value. * @return this. * @throws JSONException If the index is negative. */ public JSONArray put(int index, boolean value) throws JSONException { put(index, value ? Boolean.TRUE : Boolean.FALSE); return this; } /** * Put a value in the JSONArray, where the value will be a * JSONArray which is produced from a Collection. * @param index The subscript. * @param value A Collection value. * @return this. * @throws JSONException If the index is negative or if the value is * not finite. */ public JSONArray put(int index, Collection value) throws JSONException { put(index, new JSONArray(value)); return this; } /** * Put or replace a double value. If the index is greater than the length of * the JSONArray, then null elements will be added as necessary to pad * it out. * @param index The subscript. * @param value A double value. * @return this. * @throws JSONException If the index is negative or if the value is * not finite. */ public JSONArray put(int index, double value) throws JSONException { put(index, new Double(value)); return this; } /** * Put or replace an int value. If the index is greater than the length of * the JSONArray, then null elements will be added as necessary to pad * it out. * @param index The subscript. * @param value An int value. * @return this. * @throws JSONException If the index is negative. */ public JSONArray put(int index, int value) throws JSONException { put(index, new Integer(value)); return this; } /** * Put or replace a long value. If the index is greater than the length of * the JSONArray, then null elements will be added as necessary to pad * it out. * @param index The subscript. * @param value A long value. * @return this. * @throws JSONException If the index is negative. */ public JSONArray put(int index, long value) throws JSONException { put(index, new Long(value)); return this; } /** * Put a value in the JSONArray, where the value will be a * JSONObject which is produced from a Map. * @param index The subscript. * @param value The Map value. * @return this. * @throws JSONException If the index is negative or if the the value is * an invalid number. */ public JSONArray put(int index, Map value) throws JSONException { put(index, new JSONObject(value)); return this; } /** * Put or replace an object value in the JSONArray. If the index is greater * than the length of the JSONArray, then null elements will be added as * necessary to pad it out. * @param index The subscript. * @param value The value to put into the array. The value should be a * Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the * JSONObject.NULL object. * @return this. * @throws JSONException If the index is negative or if the the value is * an invalid number. */ public JSONArray put(int index, Object value) throws JSONException { JSONObject.testValidity(value); if (index < 0) { throw new JSONException("JSONArray[" + index + "] not found."); } if (index < length()) { this.myArrayList.set(index, value); } else { while (index != length()) { put(JSONObject.NULL); } put(value); } return this; } /** * Remove a index and close the hole. * @param index The index of the element to be removed. * @return The value that was associated with the index, * or null if there was no value. */ public Object remove(int index) { Object o = opt(index); this.myArrayList.remove(index); return o; } /** * Produce a JSONObject by combining a JSONArray of names with the values * of this JSONArray. * @param names A JSONArray containing a list of key strings. These will be * paired with the values. * @return A JSONObject, or null if there are no names or if this JSONArray * has no values. * @throws JSONException If any of the names are null. */ public JSONObject toJSONObject(JSONArray names) throws JSONException { if (names == null || names.length() == 0 || length() == 0) { return null; } JSONObject jo = new JSONObject(); for (int i = 0; i < names.length(); i += 1) { jo.put(names.getString(i), this.opt(i)); } return jo; } /** * Make a JSON text of this JSONArray. For compactness, no * unnecessary whitespace is added. If it is not possible to produce a * syntactically correct JSON text then null will be returned instead. This * could occur if the array contains an invalid number. * <p> * Warning: This method assumes that the data structure is acyclical. * * @return a printable, displayable, transmittable * representation of the array. */ @Override public String toString() { try { return '[' + join(",") + ']'; } catch (Exception e) { return null; } } /** * Make a prettyprinted JSON text of this JSONArray. * Warning: This method assumes that the data structure is acyclical. * @param indentFactor The number of spaces to add to each level of * indentation. * @return a printable, displayable, transmittable * representation of the object, beginning * with <code>[</code>&nbsp;<small>(left bracket)</small> and ending * with <code>]</code>&nbsp;<small>(right bracket)</small>. * @throws JSONException */ public String toString(int indentFactor) throws JSONException { return toString(indentFactor, 0); } /** * Make a prettyprinted JSON text of this JSONArray. * Warning: This method assumes that the data structure is acyclical. * @param indentFactor The number of spaces to add to each level of * indentation. * @param indent The indention of the top level. * @return a printable, displayable, transmittable * representation of the array. * @throws JSONException */ String toString(int indentFactor, int indent) throws JSONException { int len = length(); if (len == 0) { return "[]"; } int i; StringBuffer sb = new StringBuffer("["); if (len == 1) { sb.append(JSONObject.valueToString(this.myArrayList.get(0), indentFactor, indent)); } else { int newindent = indent + indentFactor; sb.append('\n'); for (i = 0; i < len; i += 1) { if (i > 0) { sb.append(",\n"); } for (int j = 0; j < newindent; j += 1) { sb.append(' '); } sb.append(JSONObject.valueToString(this.myArrayList.get(i), indentFactor, newindent)); } sb.append('\n'); for (i = 0; i < indent; i += 1) { sb.append(' '); } } sb.append(']'); return sb.toString(); } /** * Write the contents of the JSONArray as JSON text to a writer. * For compactness, no whitespace is added. * <p> * Warning: This method assumes that the data structure is acyclical. * * @return The writer. * @throws JSONException */ public Writer write(Writer writer) throws JSONException { try { boolean b = false; int len = length(); writer.write('['); for (int i = 0; i < len; i += 1) { if (b) { writer.write(','); } Object v = this.myArrayList.get(i); if (v instanceof JSONObject) { ((JSONObject)v).write(writer); } else if (v instanceof JSONArray) { ((JSONArray)v).write(writer); } else { writer.write(JSONObject.valueToString(v)); } b = true; } writer.write(']'); return writer; } catch (IOException e) { throw new JSONException(e); } } }
false
community_shell_src_main_java_org_neo4j_shell_util_json_JSONArray.java
1,615
public abstract class AsciiDocGenerator { private static final String DOCUMENTATION_END = "\n...\n"; private final Logger log = Logger.getLogger( AsciiDocGenerator.class.getName() ); protected final String title; protected String section; protected String description = null; protected GraphDatabaseService graph; protected static final String SNIPPET_MARKER = "@@"; protected Map<String, String> snippets = new HashMap<String, String>(); private static final Map<String, Integer> counters = new HashMap<String, Integer>(); public AsciiDocGenerator( final String title, final String section ) { this.section = section; this.title = title.replace( "_", " " ); } public AsciiDocGenerator setGraph( GraphDatabaseService graph ) { this.graph = graph; return this; } public String getTitle() { return title; } public AsciiDocGenerator setSection(final String section) { this.section = section; return this; } /** * Add a description to the test (in asciidoc format). Adding multiple * descriptions will yield one paragraph per description. * * @param description the description */ public AsciiDocGenerator description( final String description ) { if ( description == null ) { throw new IllegalArgumentException( "The description can not be null" ); } String content; int pos = description.indexOf( DOCUMENTATION_END ); if ( pos != -1 ) { content = description.substring( 0, pos ); } else { content = description; } if ( this.description == null ) { this.description = content; } else { this.description += "\n\n" + content; } return this; } protected void line( final Writer fw, final String string ) throws IOException { fw.append( string ); fw.append( "\n" ); } public static Writer getFW( String dir, String title ) { try { File dirs = new File( dir ); String name = title.replace( " ", "-" ) .toLowerCase() + ".asciidoc"; return getFW( dirs, name ); } catch ( Exception e ) { e.printStackTrace(); throw new RuntimeException( e ); } } public static Writer getFW( File dir, String filename ) { try { if ( !dir.exists() ) { dir.mkdirs(); } File out = new File( dir, filename ); if ( out.exists() ) { out.delete(); } if ( !out.createNewFile() ) { throw new RuntimeException( "File exists: " + out.getAbsolutePath() ); } return new OutputStreamWriter( new FileOutputStream( out, false ), "UTF-8" ); } catch ( Exception e ) { e.printStackTrace(); throw new RuntimeException( e ); } } public static String dumpToSeparateFile( File dir, String testId, String content ) { if ( content == null || content.isEmpty() ) { throw new IllegalArgumentException( "The content can not be empty(" + content + ")." ); } String filename = testId + ".asciidoc"; Writer writer = AsciiDocGenerator.getFW( new File( dir, "includes" ), filename ); String title = ""; char firstChar = content.charAt( 0 ); if ( firstChar == '.' || firstChar == '_' ) { int pos = content.indexOf( '\n' ); if ( pos != -1 ) { title = content.substring( 0, pos + 1 ); content = content.substring( pos + 1 ); } } try { writer.write( content ); } catch ( IOException e ) { e.printStackTrace(); } finally { try { writer.close(); } catch ( IOException e ) { e.printStackTrace(); } } return title + "include::includes/" + filename + "[]\n"; } public static String dumpToSeparateFileWithType( File dir, String type, String content ) { if ( type == null || type.isEmpty() ) { throw new IllegalArgumentException( "The type can not be null or empty: [" + type + "]" ); } String key = dir.getAbsolutePath() + type; Integer counter = counters.get( key ); if ( counter == null ) { counter = 0; } counter++; counters.put( key, counter ); String testId = type + "-" + String.valueOf( counter ); return dumpToSeparateFile( dir, testId, content ); } public static PrintWriter getPrintWriter( String dir, String title ) { return new PrintWriter( getFW( dir, title ) ); } public static String getPath( Class<?> source ) { return source.getPackage() .getName() .replace( ".", "/" ) + "/" + source.getSimpleName() + ".java"; } protected String replaceSnippets( String description, File dir, String title ) { for (String key : snippets.keySet()) { description = replaceSnippet( description, key, dir, title ); } if(description.contains( SNIPPET_MARKER )) { int indexOf = description.indexOf( SNIPPET_MARKER ); String snippet = description.substring( indexOf, description.indexOf( "\n", indexOf ) ); log.severe( "missing snippet ["+snippet+"] in " + description); } return description; } private String replaceSnippet( String description, String key, File dir, String title ) { String snippetString = SNIPPET_MARKER + key; if ( description.contains( snippetString + "\n" ) ) { String include = dumpToSeparateFile( dir, title + "-" + key, snippets.get( key ) ); description = description.replace( snippetString + "\n", include ); } else { log.severe( "Could not find " + snippetString + "\\n in " + description ); } return description; } /** * Add snippets that will be replaced into corresponding. * * A snippet needs to be on its own line, terminated by "\n". * * @@snippetname placeholders in the content of the description. * * @param key the snippet key, without @@ * @param content the content to be inserted */ public void addSnippet( String key, String content ) { snippets.put( key, content ); } /** * Added one or more source snippets from test sources, available from * javadoc using * * @@tagName. * * @param source the class where the snippet is found * @param tagNames the tag names which should be included */ public void addTestSourceSnippets( Class<?> source, String... tagNames ) { for ( String tagName : tagNames ) { addSnippet( tagName, sourceSnippet( tagName, source, "test-sources" ) ); } } /** * Added one or more source snippets, available from javadoc using * * @@tagName. * * @param source the class where the snippet is found * @param tagNames the tag names which should be included */ public void addSourceSnippets( Class<?> source, String... tagNames ) { for ( String tagName : tagNames ) { addSnippet( tagName, sourceSnippet( tagName, source, "sources" ) ); } } private static String sourceSnippet( String tagName, Class<?> source, String classifier ) { return "[snippet,java]\n" + "----\n" + "component=${project.artifactId}\n" + "source=" + getPath( source ) + "\n" + "classifier=" + classifier + "\n" + "tag=" + tagName + "\n" + "----\n"; } public void addGithubTestSourceLink( String key, Class<?> source, String dir ) { githubLink( key, source, dir, "test" ); } public void addGithubSourceLink( String key, Class<?> source, String dir ) { githubLink( key, source, dir, "main" ); } private void githubLink( String key, Class<?> source, String dir, String mainOrTest ) { String path = "https://github.com/neo4j/neo4j/blob/{neo4j-git-tag}/"; if ( dir != null ) { path += dir + "/"; } path += "src/" + mainOrTest + "/java/" + getPath( source ); path += "[" + source.getSimpleName() + ".java]\n"; addSnippet( key, path ); } }
false
community_kernel_src_test_java_org_neo4j_test_AsciiDocGenerator.java
1,616
public class AwaitAnswer<T> implements Answer<T> { public static AwaitAnswer<Void> afterAwaiting( CountDownLatch latch ) { return new AwaitAnswer<Void>( latch, null ); } private final CountDownLatch latch; private final Answer<T> result; public AwaitAnswer( CountDownLatch latch, Answer<T> result ) { this.latch = latch; this.result = result; } @Override public T answer( InvocationOnMock invocation ) throws Throwable { latch.await(); return result == null ? null : result.answer( invocation ); } public <R> Answer<R> then( Answer<R> result ) { return new AwaitAnswer<R>( latch, result ); } @SuppressWarnings("unchecked") public <R> Answer<R> thenReturn( R result ) { return then( (Answer<R>) new Returns( result ) ); } @SuppressWarnings("unchecked") public <R> Answer<R> thenThrow( Throwable exception ) { return then( (Answer<R>) new ThrowsException( exception ) ); } }
false
community_kernel_src_test_java_org_neo4j_test_AwaitAnswer.java
1,617
@Service.Implementation(App.class) public class Start extends TransactionProvidingApp { private ExecutionEngine engine; @Override public String getDescription() { String className = this.getClass().getSimpleName().toUpperCase(); return MessageFormat.format( "Executes a Cypher query. Usage: {0} <rest of query>;\nExample: MATCH " + "(me)-[:KNOWS]->(you) RETURN you.name;\nwhere '{'self'}' will be replaced with the current location in " + "the graph.Please, note that the query must end with a semicolon. Other parameters are\ntaken from " + "shell variables, see ''help export''.", className ); } @Override protected Continuation exec( AppCommandParser parser, Session session, Output out ) throws ShellException, RemoteException { String query = parser.getLine().trim(); if ( isComplete( query ) ) { try { final long startTime = System.currentTimeMillis(); ExecutionResult result = getEngine().execute( trimQuery( query ), getParameters( session ) ); handleResult( out, result, startTime, session, parser ); } catch ( CypherException e ) { throw ShellException.wrapCause( e ); } return Continuation.INPUT_COMPLETE; } else { return Continuation.INPUT_INCOMPLETE; } } protected String trimQuery( String query ) { return query.substring( 0, query.lastIndexOf( ";" ) ); } protected void handleResult( Output out, ExecutionResult result, long startTime, Session session, AppCommandParser parser ) throws RemoteException, ShellException { printResult( out, result, startTime ); } private void printResult( Output out, ExecutionResult result, long startTime ) throws RemoteException { result.toString( new PrintWriter( new OutputAsWriter( out ) ) ); out.println( (now() - startTime) + " ms" ); } protected StringLogger getCypherLogger() { DependencyResolver dependencyResolver = getServer().getDb().getDependencyResolver(); Logging logging = dependencyResolver.resolveDependency( Logging.class ); return logging.getMessagesLog( ExecutionEngine.class ); } protected Map<String, Object> getParameters(Session session) throws ShellException { try { NodeOrRelationship self = getCurrent( session ); session.set( "self", self.isNode() ? self.asNode() : self.asRelationship() ); } catch ( ShellException e ) { // OK, current didn't exist } return session.asMap(); } protected boolean isComplete( String query ) { return query.endsWith( ";" ); } protected ExecutionEngine getEngine() { if ( this.engine == null ) { synchronized ( this ) { if ( this.engine == null ) { this.engine = new ExecutionEngine( getServer().getDb(), getCypherLogger() ); } } } return this.engine; } protected long now() { return System.currentTimeMillis(); } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_cypher_Start.java
1,618
public class BatchTransaction implements AutoCloseable { private static final int DEFAULT_INTERMEDIARY_SIZE = 10000; public static BatchTransaction beginBatchTx( GraphDatabaseService db ) { return new BatchTransaction( db ); } private final GraphDatabaseService db; private Transaction tx; private int txSize; private int total; private int intermediarySize = DEFAULT_INTERMEDIARY_SIZE; private ProgressListener progressListener = ProgressListener.NONE; private BatchTransaction( GraphDatabaseService db ) { this.db = db; beginTx(); } private void beginTx() { this.tx = db.beginTx(); } public GraphDatabaseService getDb() { return db; } public boolean increment() { return increment( 1 ); } public boolean increment( int count ) { txSize += count; total += count; progressListener.add( count ); if ( txSize >= intermediarySize ) { txSize = 0; intermediaryCommit(); return true; } return false; } public void intermediaryCommit() { closeTx(); beginTx(); } private void closeTx() { tx.success(); tx.close(); } @Override public void close() { closeTx(); progressListener.done(); } public int total() { return total; } public BatchTransaction withIntermediarySize( int intermediarySize ) { this.intermediarySize = intermediarySize; return this; } public BatchTransaction withProgress( ProgressListener progressListener ) { this.progressListener = progressListener; this.progressListener.started(); return this; } }
false
community_kernel_src_test_java_org_neo4j_test_BatchTransaction.java
1,619
public class EmbeddedDatabaseRule extends DatabaseRule { private final TempDirectory temp; public EmbeddedDatabaseRule() { this.temp = new TempDirectory() { private final TemporaryFolder folder = new TemporaryFolder(); @Override public File root() { return folder.getRoot(); } @Override public void delete() { folder.delete(); } @Override public void create() throws IOException { folder.create(); } }; } public EmbeddedDatabaseRule( final Class<?> testClass ) { this.temp = new TempDirectory() { private final TargetDirectory targetDirectory = TargetDirectory.forTest( testClass ); private File dbDir; @Override public File root() { return dbDir; } @Override public void delete() throws IOException { targetDirectory.cleanup(); } @Override public void create() { dbDir = targetDirectory.makeGraphDbDir(); } }; } @Override protected GraphDatabaseFactory newFactory() { return new GraphDatabaseFactory(); } @Override protected GraphDatabaseBuilder newBuilder(GraphDatabaseFactory factory ) { return factory.newEmbeddedDatabaseBuilder( temp.root().getAbsolutePath() ); } @Override protected void createResources() throws IOException { temp.create(); } @Override protected void deleteResources() { try { temp.delete(); } catch ( IOException e ) { throw new RuntimeException( e ); } } private interface TempDirectory { File root(); void create() throws IOException; void delete() throws IOException; } }
false
community_kernel_src_test_java_org_neo4j_test_EmbeddedDatabaseRule.java
1,620
public class DumpTxLog { public static void main( String[] args ) throws IOException { FileSystemAbstraction fileSystemAbstraction = new DefaultFileSystemAbstraction(); String file = arg( args, 0, "graph db store directory or file" ); if ( new File( file ).isDirectory() ) // Assume store directory filterTxLog( fileSystemAbstraction, file, DUMP ); else // Point out a specific file filterTxLog( fileSystemAbstraction, new File( file ), DUMP ); } private static String arg( String[] args, int i, String failureMessage ) { if ( i >= args.length ) { System.out.println( "Missing " + failureMessage ); System.exit( 1 ); } return args[i]; } }
false
community_kernel_src_test_java_org_neo4j_test_DumpTxLog.java
1,621
public class DoubleLatch { private final CountDownLatch startSignal; private final CountDownLatch finishSignal; private final int numberOfContestants; public DoubleLatch() { this( 1 ); } public DoubleLatch( int numberOfContestants ) { this.numberOfContestants = numberOfContestants; this.startSignal = new CountDownLatch( numberOfContestants ); this.finishSignal = new CountDownLatch( numberOfContestants ); } public int getNumberOfContestants() { return numberOfContestants; } public void startAndAwaitFinish() { start(); awaitLatch( finishSignal ); } public void awaitStart() { awaitLatch( startSignal ); } public void start() { startSignal.countDown(); awaitLatch( startSignal ); } public void finish() { finishSignal.countDown(); } public void awaitFinish() { awaitLatch( finishSignal ); } public static void awaitLatch( CountDownLatch latch ) { try { latch.await(); } catch ( InterruptedException e ) { Thread.interrupted(); throw new RuntimeException( e ); } } @Override public String toString() { return super.toString() + "[Start[" + startSignal.getCount() + "], Finish[" + finishSignal.getCount() + "]]"; } }
false
community_kernel_src_test_java_org_neo4j_test_DoubleLatch.java
1,622
private static class PropertiesRep implements Serializable { private final Map<String, Serializable> props = new HashMap<String, Serializable>(); private final String entityToString; private final long entityId; PropertiesRep( PropertyContainer entity, long id ) { this.entityId = id; this.entityToString = entity.toString(); for ( String key : entity.getPropertyKeys() ) { Serializable value = (Serializable) entity.getProperty( key, null ); // We do this because the node may have changed since we did getPropertyKeys() if ( value != null ) { if ( value.getClass().isArray() ) { props.put( key, new ArrayList<Object>( Arrays.asList( IoPrimitiveUtils.asArray( value ) ) ) ); } else { props.put( key, value ); } } } } protected boolean compareWith( PropertiesRep other, DiffReport diff ) { boolean equals = props.equals( other.props ); if ( !equals ) diff.add( "Properties diff for " + entityToString + " mine:" + props + ", other:" + other.props ); return equals; } @Override public int hashCode() { return props.hashCode(); } @Override public String toString() { return props.toString(); } }
false
community_kernel_src_test_java_org_neo4j_test_DbRepresentation.java
1,623
private static class NodeRep implements Serializable { private final PropertiesRep properties; private final Map<Long, PropertiesRep> outRelationships = new HashMap<Long, PropertiesRep>(); private final long highestRelationshipId; private final long id; private final Map<String, Map<String, Serializable>> index; NodeRep( GraphDatabaseService db, Node node, boolean includeIndexes ) { id = node.getId(); properties = new PropertiesRep( node, node.getId() ); long highestRel = 0; for ( Relationship rel : node.getRelationships( Direction.OUTGOING ) ) { outRelationships.put( rel.getId(), new PropertiesRep( rel, rel.getId() ) ); highestRel = Math.max( highestRel, rel.getId() ); } this.highestRelationshipId = highestRel; this.index = includeIndexes ? checkIndex( db ) : null; } private Map<String, Map<String, Serializable>> checkIndex( GraphDatabaseService db ) { Map<String, Map<String, Serializable>> result = new HashMap<String, Map<String,Serializable>>(); for (String indexName : db.index().nodeIndexNames()) { Map<String, Serializable> thisIndex = new HashMap<String, Serializable>(); Index<Node> tempIndex = db.index().forNodes( indexName ); for (Map.Entry<String, Serializable> property : properties.props.entrySet()) { IndexHits<Node> content = tempIndex.get( property.getKey(), property.getValue() ); if (content.hasNext()) { for (Node hit : content) { if (hit.getId() == id) { thisIndex.put( property.getKey(), property.getValue() ); break; } } } } result.put( indexName, thisIndex ); } return result; } /* * Yes, this is not the best way to do it - hash map does a deep equals. However, * if things go wrong, this way give the ability to check where the inequality * happened. If you feel strongly about this, feel free to change. * Admittedly, the implementation could use some cleanup. */ private void compareIndex( NodeRep other, DiffReport diff ) { if ( other.index == index ) return; Collection<String> allIndexes = new HashSet<String>(); allIndexes.addAll( index.keySet() ); allIndexes.addAll( other.index.keySet() ); for ( String indexName : allIndexes ) { if ( !index.containsKey( indexName ) ) { diff.add( this + " isn't indexed in " + indexName + " for mine" ); continue; } if ( !other.index.containsKey( indexName ) ) { diff.add( this + " isn't indexed in " + indexName + " for other" ); continue; } Map<String, Serializable> thisIndex = index.get( indexName ); Map<String, Serializable> otherIndex = other.index.get( indexName ); if ( thisIndex.size() != otherIndex.size() ) { diff.add( "other index had a different mapping count than me for node " + this + " mine:" + thisIndex + ", other:" + otherIndex ); continue; } for ( Map.Entry<String, Serializable> indexEntry : thisIndex.entrySet() ) { if ( !indexEntry.getValue().equals( otherIndex.get( indexEntry.getKey() ) ) ) { diff.add( "other index had a different value indexed for " + indexEntry.getKey() + "=" + indexEntry.getValue() + ", namely " + otherIndex.get( indexEntry.getKey() ) + " for " + this ); } } } } protected void compareWith( NodeRep other, DiffReport diff ) { if ( other.id != id ) diff.add( "Id differs mine:" + id + ", other:" + other.id ); properties.compareWith( other.properties, diff ); if ( index != null && other.index != null ) compareIndex( other, diff ); compareRelationships( other, diff ); } private void compareRelationships( NodeRep other, DiffReport diff ) { for ( PropertiesRep rel : outRelationships.values() ) { PropertiesRep otherRel = other.outRelationships.get( rel.entityId ); if ( otherRel == null ) { diff.add( "I have relationship " + rel.entityId + " which other don't" ); continue; } rel.compareWith( otherRel, diff ); } for ( Long id : other.outRelationships.keySet() ) { if ( !outRelationships.containsKey( id ) ) diff.add( "Other has relationship " + id + " which I don't" ); } } @Override public int hashCode() { int result = 7; result += properties.hashCode()*7; result += outRelationships.hashCode()*13; result += id * 17; if ( index != null ) result += index.hashCode() * 19; return result; } @Override public String toString() { return "<id: " + id + " props: " + properties + ", rels: " + outRelationships + ">"; } }
false
community_kernel_src_test_java_org_neo4j_test_DbRepresentation.java
1,624
private static class CollectionDiffReport implements DiffReport { private final Collection<String> collection; public CollectionDiffReport( Collection<String> collection ) { this.collection = collection; } @Override public void add( String report ) { collection.add( report ); } }
false
community_kernel_src_test_java_org_neo4j_test_DbRepresentation.java
1,625
public class DbRepresentation implements Serializable { private final Map<Long, NodeRep> nodes = new TreeMap<Long, NodeRep>(); private long highestNodeId; private long highestRelationshipId; public static DbRepresentation of( GraphDatabaseService db ) { return of( db, true ); } public static DbRepresentation of( GraphDatabaseService db, boolean includeIndexes ) { Transaction tx = db.beginTx(); try { DbRepresentation result = new DbRepresentation(); for ( Node node : GlobalGraphOperations.at( db ).getAllNodes() ) { NodeRep nodeRep = new NodeRep( db, node, includeIndexes ); result.nodes.put( node.getId(), nodeRep ); result.highestNodeId = Math.max( node.getId(), result.highestNodeId ); result.highestRelationshipId = Math.max( nodeRep.highestRelationshipId, result.highestRelationshipId ); } return result; } finally { tx.finish(); } } public static DbRepresentation of( File storeDir ) { return of( storeDir, true ); } public static DbRepresentation of( File storeDir, boolean includeIndexes ) { GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase( storeDir.getPath() ); try { return of( db, includeIndexes ); } finally { db.shutdown(); } } public long getHighestNodeId() { return highestNodeId; } public long getHighestRelationshipId() { return highestRelationshipId; } @Override public boolean equals( Object obj ) { return compareWith( (DbRepresentation) obj ).isEmpty(); } public Collection<String> compareWith( DbRepresentation other ) { Collection<String> diffList = new ArrayList<String>(); DiffReport diff = new CollectionDiffReport( diffList ); for ( NodeRep node : nodes.values() ) { NodeRep otherNode = other.nodes.get( node.id ); if ( otherNode == null ) { diff.add( "I have node " + node.id + " which other don't" ); continue; } node.compareWith( otherNode, diff ); } for ( Long id : other.nodes.keySet() ) { if ( !nodes.containsKey( id ) ) diff.add( "Other has node " + id + " which I don't" ); } return diffList; } @Override public int hashCode() { return nodes.hashCode(); } @Override public String toString() { return nodes.toString(); } private static class NodeRep implements Serializable { private final PropertiesRep properties; private final Map<Long, PropertiesRep> outRelationships = new HashMap<Long, PropertiesRep>(); private final long highestRelationshipId; private final long id; private final Map<String, Map<String, Serializable>> index; NodeRep( GraphDatabaseService db, Node node, boolean includeIndexes ) { id = node.getId(); properties = new PropertiesRep( node, node.getId() ); long highestRel = 0; for ( Relationship rel : node.getRelationships( Direction.OUTGOING ) ) { outRelationships.put( rel.getId(), new PropertiesRep( rel, rel.getId() ) ); highestRel = Math.max( highestRel, rel.getId() ); } this.highestRelationshipId = highestRel; this.index = includeIndexes ? checkIndex( db ) : null; } private Map<String, Map<String, Serializable>> checkIndex( GraphDatabaseService db ) { Map<String, Map<String, Serializable>> result = new HashMap<String, Map<String,Serializable>>(); for (String indexName : db.index().nodeIndexNames()) { Map<String, Serializable> thisIndex = new HashMap<String, Serializable>(); Index<Node> tempIndex = db.index().forNodes( indexName ); for (Map.Entry<String, Serializable> property : properties.props.entrySet()) { IndexHits<Node> content = tempIndex.get( property.getKey(), property.getValue() ); if (content.hasNext()) { for (Node hit : content) { if (hit.getId() == id) { thisIndex.put( property.getKey(), property.getValue() ); break; } } } } result.put( indexName, thisIndex ); } return result; } /* * Yes, this is not the best way to do it - hash map does a deep equals. However, * if things go wrong, this way give the ability to check where the inequality * happened. If you feel strongly about this, feel free to change. * Admittedly, the implementation could use some cleanup. */ private void compareIndex( NodeRep other, DiffReport diff ) { if ( other.index == index ) return; Collection<String> allIndexes = new HashSet<String>(); allIndexes.addAll( index.keySet() ); allIndexes.addAll( other.index.keySet() ); for ( String indexName : allIndexes ) { if ( !index.containsKey( indexName ) ) { diff.add( this + " isn't indexed in " + indexName + " for mine" ); continue; } if ( !other.index.containsKey( indexName ) ) { diff.add( this + " isn't indexed in " + indexName + " for other" ); continue; } Map<String, Serializable> thisIndex = index.get( indexName ); Map<String, Serializable> otherIndex = other.index.get( indexName ); if ( thisIndex.size() != otherIndex.size() ) { diff.add( "other index had a different mapping count than me for node " + this + " mine:" + thisIndex + ", other:" + otherIndex ); continue; } for ( Map.Entry<String, Serializable> indexEntry : thisIndex.entrySet() ) { if ( !indexEntry.getValue().equals( otherIndex.get( indexEntry.getKey() ) ) ) { diff.add( "other index had a different value indexed for " + indexEntry.getKey() + "=" + indexEntry.getValue() + ", namely " + otherIndex.get( indexEntry.getKey() ) + " for " + this ); } } } } protected void compareWith( NodeRep other, DiffReport diff ) { if ( other.id != id ) diff.add( "Id differs mine:" + id + ", other:" + other.id ); properties.compareWith( other.properties, diff ); if ( index != null && other.index != null ) compareIndex( other, diff ); compareRelationships( other, diff ); } private void compareRelationships( NodeRep other, DiffReport diff ) { for ( PropertiesRep rel : outRelationships.values() ) { PropertiesRep otherRel = other.outRelationships.get( rel.entityId ); if ( otherRel == null ) { diff.add( "I have relationship " + rel.entityId + " which other don't" ); continue; } rel.compareWith( otherRel, diff ); } for ( Long id : other.outRelationships.keySet() ) { if ( !outRelationships.containsKey( id ) ) diff.add( "Other has relationship " + id + " which I don't" ); } } @Override public int hashCode() { int result = 7; result += properties.hashCode()*7; result += outRelationships.hashCode()*13; result += id * 17; if ( index != null ) result += index.hashCode() * 19; return result; } @Override public String toString() { return "<id: " + id + " props: " + properties + ", rels: " + outRelationships + ">"; } } private static class PropertiesRep implements Serializable { private final Map<String, Serializable> props = new HashMap<String, Serializable>(); private final String entityToString; private final long entityId; PropertiesRep( PropertyContainer entity, long id ) { this.entityId = id; this.entityToString = entity.toString(); for ( String key : entity.getPropertyKeys() ) { Serializable value = (Serializable) entity.getProperty( key, null ); // We do this because the node may have changed since we did getPropertyKeys() if ( value != null ) { if ( value.getClass().isArray() ) { props.put( key, new ArrayList<Object>( Arrays.asList( IoPrimitiveUtils.asArray( value ) ) ) ); } else { props.put( key, value ); } } } } protected boolean compareWith( PropertiesRep other, DiffReport diff ) { boolean equals = props.equals( other.props ); if ( !equals ) diff.add( "Properties diff for " + entityToString + " mine:" + props + ", other:" + other.props ); return equals; } @Override public int hashCode() { return props.hashCode(); } @Override public String toString() { return props.toString(); } } private static interface DiffReport { void add( String report ); } private static class CollectionDiffReport implements DiffReport { private final Collection<String> collection; public CollectionDiffReport( Collection<String> collection ) { this.collection = collection; } @Override public void add( String report ) { collection.add( report ); } } }
false
community_kernel_src_test_java_org_neo4j_test_DbRepresentation.java
1,626
{ @Override public TO apply( GraphDatabaseService graphDb ) { return function.apply( from ); } } );
false
community_kernel_src_test_java_org_neo4j_test_DatabaseRule.java
1,627
{ @Override public TO apply( final FROM from ) { return executeAndCommit( new Function<GraphDatabaseService, TO>() { @Override public TO apply( GraphDatabaseService graphDb ) { return function.apply( from ); } } ); } };
false
community_kernel_src_test_java_org_neo4j_test_DatabaseRule.java
1,628
public abstract class DatabaseRule extends ExternalResource { GraphDatabaseBuilder databaseBuilder; GraphDatabaseAPI database; private String storeDir; public <T> T when( Function<GraphDatabaseService, T> function ) { return function.apply( getGraphDatabaseService() ); } public <T> T executeAndCommit( Function<? super GraphDatabaseService, T> function ) { return transaction( function, true ); } public <T> T executeAndRollback( Function<? super GraphDatabaseService, T> function ) { return transaction( function, false ); } public <FROM, TO> AlgebraicFunction<FROM, TO> tx( final Function<FROM, TO> function ) { return new AlgebraicFunction<FROM, TO>() { @Override public TO apply( final FROM from ) { return executeAndCommit( new Function<GraphDatabaseService, TO>() { @Override public TO apply( GraphDatabaseService graphDb ) { return function.apply( from ); } } ); } }; } private <T> T transaction( Function<? super GraphDatabaseService, T> function, boolean commit ) { try ( Transaction tx = database.beginTx() ) { T result = function.apply( database ); if ( commit ) { tx.success(); } return result; } } @Override protected void before() throws Throwable { create(); } @Override protected void after() { shutdown(); } @SuppressWarnings("deprecation") public void create() throws IOException { createResources(); try { GraphDatabaseFactory factory = newFactory(); configure( factory ); databaseBuilder = newBuilder( factory ); configure( databaseBuilder ); database = (GraphDatabaseAPI) databaseBuilder.newGraphDatabase(); storeDir = database.getStoreDir(); } catch ( RuntimeException e ) { deleteResources(); throw e; } } protected void deleteResources() { } protected void createResources() throws IOException { } protected abstract GraphDatabaseFactory newFactory(); protected abstract GraphDatabaseBuilder newBuilder( GraphDatabaseFactory factory ); protected void configure( GraphDatabaseFactory databaseFactory ) { // Override to configure the database factory } protected void configure( GraphDatabaseBuilder builder ) { // Override to configure the database } public GraphDatabaseService getGraphDatabaseService() { return database; } public GraphDatabaseAPI getGraphDatabaseAPI() { return database; } public static interface RestartAction { void run( FileSystemAbstraction fs, File storeDirectory ); } public void restartDatabase( RestartAction action ) { FileSystemAbstraction fs = database.getDependencyResolver().resolveDependency( FileSystemAbstraction.class ); database.shutdown(); action.run( fs, new File( storeDir ) ); database = (GraphDatabaseAPI) databaseBuilder.newGraphDatabase(); } public void shutdown() { try { if ( database != null ) { database.shutdown(); } } finally { deleteResources(); database = null; } } public void clearCache() { getGraphDatabaseAPI().getDependencyResolver().resolveDependency( NodeManager.class ).clearCache(); } }
false
community_kernel_src_test_java_org_neo4j_test_DatabaseRule.java
1,629
{ @Override public Void apply( GraphDatabaseService graphDb ) { graphDb.schema().awaitIndexesOnline( timeout, unit ); return null; } };
false
community_kernel_src_test_java_org_neo4j_test_DatabaseFunctions.java
1,630
{ @Override public Void apply( GraphDatabaseService graphDb ) { graphDb.schema().constraintFor( label ).assertPropertyIsUnique( propertyKey ).create(); return null; } };
false
community_kernel_src_test_java_org_neo4j_test_DatabaseFunctions.java
1,631
{ @Override public Void apply( GraphDatabaseService graphDb ) { graphDb.schema().indexFor( label ).on( propertyKey ).create(); return null; } };
false
community_kernel_src_test_java_org_neo4j_test_DatabaseFunctions.java
1,632
{ @Override public Node apply( Node node ) { node.setProperty( propertyKey, value ); return node; } };
false
community_kernel_src_test_java_org_neo4j_test_DatabaseFunctions.java
1,633
{ @Override public Node apply( Node node ) { node.addLabel( label ); return node; } };
false
community_kernel_src_test_java_org_neo4j_test_DatabaseFunctions.java
1,634
{ @Override public Node apply( GraphDatabaseService graphDb ) { return graphDb.createNode(); } };
false
community_kernel_src_test_java_org_neo4j_test_DatabaseFunctions.java
1,635
public class DatabaseFunctions { public static AlgebraicFunction<GraphDatabaseService, Node> createNode() { return new AlgebraicFunction<GraphDatabaseService, Node>() { @Override public Node apply( GraphDatabaseService graphDb ) { return graphDb.createNode(); } }; } public static AlgebraicFunction<Node, Node> addLabel( final Label label ) { return new AlgebraicFunction<Node, Node>() { @Override public Node apply( Node node ) { node.addLabel( label ); return node; } }; } public static AlgebraicFunction<Node, Node> setProperty( final String propertyKey, final Object value ) { return new AlgebraicFunction<Node, Node>() { @Override public Node apply( Node node ) { node.setProperty( propertyKey, value ); return node; } }; } public static AlgebraicFunction<GraphDatabaseService, Void> index( final Label label, final String propertyKey ) { return new AlgebraicFunction<GraphDatabaseService, Void>() { @Override public Void apply( GraphDatabaseService graphDb ) { graphDb.schema().indexFor( label ).on( propertyKey ).create(); return null; } }; } public static AlgebraicFunction<GraphDatabaseService, Void> uniquenessConstraint( final Label label, final String propertyKey ) { return new AlgebraicFunction<GraphDatabaseService, Void>() { @Override public Void apply( GraphDatabaseService graphDb ) { graphDb.schema().constraintFor( label ).assertPropertyIsUnique( propertyKey ).create(); return null; } }; } public static AlgebraicFunction<GraphDatabaseService, Void> awaitIndexesOnline( final long timeout, final TimeUnit unit ) { return new AlgebraicFunction<GraphDatabaseService, Void>() { @Override public Void apply( GraphDatabaseService graphDb ) { graphDb.schema().awaitIndexesOnline( timeout, unit ); return null; } }; } private DatabaseFunctions() { // no instances } }
false
community_kernel_src_test_java_org_neo4j_test_DatabaseFunctions.java
1,636
public class CleanupRule extends ExternalResource { private final List<Closeable> toCloseAfterwards = new ArrayList<>(); @Override protected void after() { for ( Closeable toClose : toCloseAfterwards ) { try { toClose.close(); } catch ( Exception e ) { System.out.println( "Couldn't clean up " + toClose + " after test finished" ); } } } public <T extends Closeable> T add( T toClose ) { toCloseAfterwards.add( toClose ); return toClose; } }
false
community_kernel_src_test_java_org_neo4j_test_CleanupRule.java
1,637
public class BufferingLogging implements Logging { private final BufferingLogger log = new BufferingLogger(); private final BufferingConsoleLogger console = new BufferingConsoleLogger(); @Override public StringLogger getMessagesLog( Class loggingClass ) { return log; } @Override public ConsoleLogger getConsoleLog( Class loggingClass ) { return console; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append( log.toString() ).append( format( "%n" ) ).append( console.toString() ); return builder.toString(); } }
false
community_kernel_src_test_java_org_neo4j_test_BufferingLogging.java
1,638
@Service.Implementation( App.class ) public class With extends Start { }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_cypher_With.java
1,639
@Service.Implementation( App.class ) public class Return extends Start { }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_cypher_Return.java
1,640
public class Eval extends TransactionProvidingApp { private ScriptEngineViaReflection scripting; @Override public String getDescription() { return "Pass JavaScript to be executed on the shell server, directly on the database. " + "There are predefined variables you can use:\n" + " db : the GraphDatabaseService on the server\n" + " out : output back to you (the shell client)\n" + " current : current node or relationship you stand on\n\n" + "Usage:\n" + " eval db.getReferenceNode().getProperty(\"name\")\n" + " \n" + " eval\n" + " > nodes = db.getAllNodes().iterator();\n" + " > while ( nodes.hasNext() )\n" + " > out.println( \"\" + nodes.next() );\n" + " >\n" + "So either a one-liner or type 'eval' to enter multi-line mode, where an empty line denotes the end"; } @Override protected Continuation exec( AppCommandParser parser, Session session, Output out ) throws Exception { // satisfied if: // * it ends with \n // * there's stuff after eval and no \n on the line boolean satisfied = parser.getLine().endsWith( "\n" ) || (parser.getLineWithoutApp().length() > 0 && parser.getLine().indexOf( '\n' ) == -1); if ( !satisfied ) return Continuation.INPUT_INCOMPLETE; scripting = scripting != null ? scripting : new ScriptEngineViaReflection( getServer() ); String javascriptCode = parser.getLineWithoutApp(); javascriptCode = decorateWithImports( javascriptCode, STANDARD_EVAL_IMPORTS ); Object scriptEngine = scripting.getJavascriptEngine(); scripting.addDefaultContext( scriptEngine, session, out ); Object result = scripting.interpret( scriptEngine, javascriptCode ); if ( result != null ) { out.println( result.toString() ); } return Continuation.INPUT_COMPLETE; } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_Eval.java
1,641
{ @Override public String apply( IndexDefinition index ) { return index.getLabel().name(); } };
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_Schema.java
1,642
@Service.Implementation(App.class) public class Rollback extends NonTransactionProvidingApp { @Override public String getDescription() { return "Rolls back all open transactions"; } @Override protected Continuation exec( AppCommandParser parser, Session session, Output out ) throws ShellException, RemoteException { if ( parser.getLineWithoutApp().trim().length() > 0 ) { out.println( "Error: ROLLBACK should be run without trailing arguments" ); return Continuation.INPUT_COMPLETE; } Transaction tx = Begin.currentTransaction( getServer() ); if ( tx == null ) { throw Commit.fail( session, "Not in a transaction" ); } else { try { session.remove( Variables.TX_COUNT ); tx.rollback(); out.println( "Transaction rolled back" ); return Continuation.INPUT_COMPLETE; } catch ( SystemException e ) { throw new ShellException( e.getMessage() ); } } } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_Rollback.java
1,643
@Service.Implementation( App.class ) public class Rmrel extends TransactionProvidingApp { /** * Constructs a new application which can delete relationships in Neo4j. */ public Rmrel() { this.addOptionDefinition( "f", new OptionDefinition( OptionValueType.NONE, "Force deletion, i.e. disables the connectedness check" ) ); this.addOptionDefinition( "d", new OptionDefinition( OptionValueType.NONE, "Also delete the node on the other side of the relationship if removing" + " this relationship results in it not having any relationships left" ) ); } @Override public String getDescription() { return "Deletes a relationship, also ensuring the connectedness of the graph. That check can be ignored with -f\n" + "Usage: rmrel <relationship id>\n" + " or rmrel -f <relationship id>"; } @Override protected Continuation exec( AppCommandParser parser, Session session, Output out ) throws ShellException, RemoteException { assertCurrentIsNode( session ); if ( parser.arguments().isEmpty() ) { throw new ShellException( "Must supply relationship id to delete as the first argument" ); } Node currentNode = this.getCurrent( session ).asNode(); Relationship rel = findRel( currentNode, Long.parseLong( parser.arguments().get( 0 ) ) ); rel.delete(); Node otherNode = rel.getOtherNode( currentNode ); boolean deleteOtherNodeIfEmpty = parser.options().containsKey( "d" ); if ( deleteOtherNodeIfEmpty && !otherNode.hasRelationship() ) { out.println( "Also deleted " + getDisplayName( getServer(), session, otherNode, false ) + " due to it not having any relationships left" ); otherNode.delete(); } return Continuation.INPUT_COMPLETE; } private Relationship findRel( Node currentNode, long relId ) throws ShellException { Relationship rel = getServer().getDb().getRelationshipById( relId ); if ( rel.getStartNode().equals( currentNode ) || rel.getEndNode().equals( currentNode ) ) { return rel; } throw new ShellException( "No relationship " + relId + " connected to " + currentNode ); } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_Rmrel.java
1,644
@Service.Implementation( App.class ) public class Rmnode extends TransactionProvidingApp { public Rmnode() { addOptionDefinition( "f", new OptionDefinition( OptionValueType.NONE, "Force deletion, will delete all relationships prior to deleting the node" ) ); } @Override public String getDescription() { return "Deletes a node from the graph. If no node-id argument is given the current node is deleted"; } @Override protected Continuation exec( AppCommandParser parser, Session session, Output out ) throws ShellException, RemoteException { NodeOrRelationship node = null; if ( parser.arguments().isEmpty() ) { node = getCurrent( session ); } else { long id = parseInt( parser.arguments().get( 0 ) ); try { node = wrap( getNodeById( id ) ); } catch ( NotFoundException e ) { throw new ShellException( "No node " + id + " found" ); } } if ( !node.isNode() ) { out.println( "Please select a node to delete" ); return Continuation.INPUT_COMPLETE; } boolean forceDeletion = parser.options().containsKey( "f" ); if ( forceDeletion ) { for ( Relationship relationship : node.asNode().getRelationships() ) { out.println( "Relationship " + getDisplayName( getServer(), session, relationship, true, false ) + " deleted" ); relationship.delete(); } } if ( node.asNode().hasRelationship() ) { throw new ShellException( getDisplayName( getServer(), session, node.asNode(), false ) + " cannot be deleted because it still has relationships. Use -f to force deletion of its relationships" ); } node.asNode().delete(); return Continuation.INPUT_COMPLETE; } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_Rmnode.java
1,645
@Service.Implementation( App.class ) public class Rm extends TransactionProvidingApp { { addOptionDefinition( "p", new OptionDefinition( OptionValueType.NONE, "Removes a property" ) ); addOptionDefinition( "l", new OptionDefinition( OptionValueType.MUST, "Removes one or more labels" ) ); } @Override public String getDescription() { return "Removes a property from the current node or relationship or label from the current node.\n" + "Usage:\n" + " rm <key>\n" + " rm -p name\n" + " rm -l PERSON"; } @Override protected Continuation exec( AppCommandParser parser, Session session, Output out ) throws Exception { NodeOrRelationship thing = getCurrent( session ); boolean forProperty = parser.options().containsKey( "p" ); boolean forLabel = parser.options().containsKey( "l" ); if ( forProperty || !forLabel ) { // Property if ( parser.arguments().isEmpty() ) { throw new ShellException( "Must supply the property key or label name to " + "remove, like: rm title" ); } String key = parser.arguments().get( 0 ); if ( thing.removeProperty( key ) == null ) { out.println( "Property '" + key + "' not found" ); } } else { Node node = thing.asNode(); for ( Label label : parseLabels( parser ) ) { node.removeLabel( label ); } } return Continuation.INPUT_COMPLETE; } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_Rm.java
1,646
@Service.Implementation( App.class ) public class Pwd extends TransactionProvidingApp { @Override public String getDescription() { return "Prints path to current node or relationship"; } @Override protected Continuation exec( AppCommandParser parser, Session session, Output out ) throws ShellException, RemoteException { String current = null; try { current = getDisplayName( getServer(), session, getCurrent( session ), false ); } catch ( ShellException e ) { current = getDisplayNameForNonExistent(); } out.println( "Current is " + current ); String path = stringifyPath( Cd.readCurrentWorkingDir( session ), session ) + current; if ( path.length() > 0 ) { out.println( path ); } return Continuation.INPUT_COMPLETE; } private String stringifyPath( List<TypedId> pathIds, Session session ) throws ShellException { if ( pathIds.isEmpty() ) { return ""; } StringBuilder path = new StringBuilder(); for ( TypedId id : pathIds ) { String displayName; try { displayName = getDisplayName( getServer(), session, id, false ); } catch ( ShellException e ) { displayName = getDisplayNameForNonExistent(); } path.append( displayName ).append( "-->" ); } return path.toString(); } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_Pwd.java
1,647
public abstract class NonTransactionProvidingApp extends TransactionProvidingApp { @Override public Continuation execute( AppCommandParser parser, Session session, Output out ) throws Exception { return this.exec( parser, session, out ); } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_NonTransactionProvidingApp.java
1,648
static class WrapRelationship extends NodeOrRelationship { private WrapRelationship( Relationship rel ) { super( rel ); } private Relationship object() { return asRelationship(); } @Override public String getType() { return TYPE_RELATIONSHIP; } @Override public long getId() { return object().getId(); } @Override public boolean hasProperty( String key ) { return object().hasProperty( key ); } @Override public Object getProperty( String key ) { return object().getProperty( key ); } @Override public Object getProperty( String key, Object defaultValue ) { return object().getProperty( key, defaultValue ); } @Override public void setProperty( String key, Object value ) { object().setProperty( key, value ); } @Override public Object removeProperty( String key ) { return object().removeProperty( key ); } @Override public Iterable<String> getPropertyKeys() { return object().getPropertyKeys(); } @Override public Iterable<Relationship> getRelationships( Direction direction ) { return new ArrayList<>(); } @Override public String toString() { return "Shell wrapped relationship [" + asRelationship() + "]"; } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_NodeOrRelationship.java
1,649
static class WrapNode extends NodeOrRelationship { private WrapNode( Node node ) { super( node ); } private Node object() { return asNode(); } @Override public String getType() { return TYPE_NODE; } @Override public long getId() { return object().getId(); } @Override public boolean hasProperty( String key ) { return object().hasProperty( key ); } @Override public Object getProperty( String key ) { return object().getProperty( key ); } @Override public Object getProperty( String key, Object defaultValue ) { return object().getProperty( key, defaultValue ); } @Override public void setProperty( String key, Object value ) { object().setProperty( key, value ); } @Override public Object removeProperty( String key ) { return object().removeProperty( key ); } @Override public Iterable<String> getPropertyKeys() { return object().getPropertyKeys(); } @Override public Iterable<Relationship> getRelationships( Direction direction ) { return object().getRelationships( direction ); } @Override public String toString() { return "Shell wrapped node [" + asNode() + "]"; } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_NodeOrRelationship.java
1,650
public abstract class NodeOrRelationship { public static final String TYPE_NODE = "n"; public static final String TYPE_RELATIONSHIP = "r"; public static NodeOrRelationship wrap( Node node ) { return new WrapNode( node ); } public static NodeOrRelationship wrap( Relationship rel ) { return new WrapRelationship( rel ); } public static NodeOrRelationship wrap( PropertyContainer entity ) { return entity instanceof Node ? wrap( (Node) entity ) : wrap( (Relationship) entity ); } private final Object nodeOrRelationship; NodeOrRelationship( Object nodeOrRelationship ) { this.nodeOrRelationship = nodeOrRelationship; } public boolean isNode() { return nodeOrRelationship instanceof Node; } public Node asNode() { return (Node) nodeOrRelationship; } public boolean isRelationship() { return nodeOrRelationship instanceof Relationship; } public Relationship asRelationship() { return (Relationship) nodeOrRelationship; } public PropertyContainer asPropertyContainer() { return (PropertyContainer) nodeOrRelationship; } public TypedId getTypedId() { return new TypedId( getType(), getId() ); } abstract String getType(); public abstract long getId(); public abstract boolean hasProperty( String key ); public abstract Object getProperty( String key ); public abstract Object getProperty( String key, Object defaultValue ); public abstract void setProperty( String key, Object value ); public abstract Object removeProperty( String key ); public abstract Iterable<String> getPropertyKeys(); public abstract Iterable<Relationship> getRelationships( Direction direction ); @Override public boolean equals( Object o ) { if ( !( o instanceof NodeOrRelationship ) ) { return false; } return getTypedId().equals( ( (NodeOrRelationship) o ).getTypedId() ); } @Override public int hashCode() { return getTypedId().hashCode(); } static class WrapNode extends NodeOrRelationship { private WrapNode( Node node ) { super( node ); } private Node object() { return asNode(); } @Override public String getType() { return TYPE_NODE; } @Override public long getId() { return object().getId(); } @Override public boolean hasProperty( String key ) { return object().hasProperty( key ); } @Override public Object getProperty( String key ) { return object().getProperty( key ); } @Override public Object getProperty( String key, Object defaultValue ) { return object().getProperty( key, defaultValue ); } @Override public void setProperty( String key, Object value ) { object().setProperty( key, value ); } @Override public Object removeProperty( String key ) { return object().removeProperty( key ); } @Override public Iterable<String> getPropertyKeys() { return object().getPropertyKeys(); } @Override public Iterable<Relationship> getRelationships( Direction direction ) { return object().getRelationships( direction ); } @Override public String toString() { return "Shell wrapped node [" + asNode() + "]"; } } static class WrapRelationship extends NodeOrRelationship { private WrapRelationship( Relationship rel ) { super( rel ); } private Relationship object() { return asRelationship(); } @Override public String getType() { return TYPE_RELATIONSHIP; } @Override public long getId() { return object().getId(); } @Override public boolean hasProperty( String key ) { return object().hasProperty( key ); } @Override public Object getProperty( String key ) { return object().getProperty( key ); } @Override public Object getProperty( String key, Object defaultValue ) { return object().getProperty( key, defaultValue ); } @Override public void setProperty( String key, Object value ) { object().setProperty( key, value ); } @Override public Object removeProperty( String key ) { return object().removeProperty( key ); } @Override public Iterable<String> getPropertyKeys() { return object().getPropertyKeys(); } @Override public Iterable<Relationship> getRelationships( Direction direction ) { return new ArrayList<>(); } @Override public String toString() { return "Shell wrapped relationship [" + asRelationship() + "]"; } } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_NodeOrRelationship.java
1,651
@Service.Implementation( App.class ) public class Mv extends TransactionProvidingApp { /** * Constructs a new "mv" application. */ public Mv() { super(); this.addOptionDefinition( "o", new OptionDefinition( OptionValueType.NONE, "To override if the key already exists" ) ); } @Override public String getDescription() { return "Renames a property on a node or relationship. " + "Usage: mv <key> <new-key>"; } @Override protected Continuation exec( AppCommandParser parser, Session session, Output out ) throws ShellException { if ( parser.arguments().size() < 2 ) { throw new ShellException( "Must supply <from-key> <to-key> " + "arguments, like: mv name \"given_name\"" ); } String fromKey = parser.arguments().get( 0 ); String toKey = parser.arguments().get( 1 ); boolean mayOverwrite = parser.options().containsKey( "o" ); NodeOrRelationship thing = getCurrent( session ); if ( !thing.hasProperty( fromKey ) ) { throw new ShellException( "Property '" + fromKey + "' doesn't exist" ); } if ( thing.hasProperty( toKey ) ) { if ( !mayOverwrite ) { throw new ShellException( "Property '" + toKey + "' already exists, supply -o flag to overwrite" ); } else { thing.removeProperty( toKey ); } } Object value = thing.removeProperty( fromKey ); thing.setProperty( toKey, value ); return Continuation.INPUT_COMPLETE; } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_Mv.java
1,652
@Service.Implementation( App.class ) public class Mkrel extends TransactionProvidingApp { public static final String KEY_LAST_CREATED_NODE = "LAST_CREATED_NODE"; public static final String KEY_LAST_CREATED_RELATIONSHIP = "LAST_CREATED_RELATIONSHIP"; /** * Constructs a new application which can create relationships and nodes * in Neo4j. */ public Mkrel() { this.addOptionDefinition( "t", new OptionDefinition( OptionValueType.MUST, "The relationship type" ) ); this.addOptionDefinition( "d", new OptionDefinition( OptionValueType.MUST, "The direction: " + this.directionAlternatives() + "." ) ); this.addOptionDefinition( "c", new OptionDefinition( OptionValueType.NONE, "Supplied if there should be created a new node" ) ); this.addOptionDefinition( "v", new OptionDefinition( OptionValueType.NONE, "Verbose mode: display created nodes/relationships" ) ); this.addOptionDefinition( "np", new OptionDefinition( OptionValueType.MUST, "Properties (a json map) to set for the new node (if one is created)" ) ); addOptionDefinition( "l", new OptionDefinition( OptionValueType.MUST, "Labels to attach to the created node (if one is created), either a single label or a JSON array" ) ); this.addOptionDefinition( "rp", new OptionDefinition( OptionValueType.MUST, "Properties (a json map) to set for the new relationship" ) ); this.addOptionDefinition( "cd", new OptionDefinition( OptionValueType.NONE, "Go to the created node, like doing 'cd'" ) ); } @Override public String getDescription() { return "Creates a relationship to a new or existing node, f.ex:\n" + "mkrel -ct KNOWS (will create a relationship to a new node)\n" + "mkrel -t KNOWS 123 (will create a relationship to node with id 123)"; } @Override protected Continuation exec( AppCommandParser parser, Session session, Output out ) throws ShellException, RemoteException { assertCurrentIsNode( session ); boolean createNode = parser.options().containsKey( "c" ); boolean suppliedNode = !parser.arguments().isEmpty(); Node node = null; if ( createNode ) { node = getServer().getDb().createNode( parseLabels( parser ) ); session.set( KEY_LAST_CREATED_NODE, "" + node.getId() ); setProperties( node, parser.options().get( "np" ) ); } else if ( suppliedNode ) { node = getNodeById( Long.parseLong( parser.arguments().get( 0 ) ) ); } else { throw new ShellException( "Must either create node (-c)" + " or supply node id as the first argument" ); } if ( parser.options().get( "t" ) == null ) { throw new ShellException( "Must supply relationship type " + "(-t <relationship-type-name>)" ); } RelationshipType type = getRelationshipType( parser.options().get( "t" ) ); Direction direction = getDirection( parser.options().get( "d" ) ); NodeOrRelationship current = getCurrent( session ); Node currentNode = current.asNode(); Node startNode = direction == Direction.OUTGOING ? currentNode : node; Node endNode = direction == Direction.OUTGOING ? node : currentNode; Relationship relationship = startNode.createRelationshipTo( endNode, type ); setProperties( relationship, parser.options().get( "rp" ) ); session.set( KEY_LAST_CREATED_RELATIONSHIP, relationship.getId() ); boolean verbose = parser.options().containsKey( "v" ); if ( createNode && verbose ) { out.println( "Node " + getDisplayName( getServer(), session, node, false ) + " created" ); } if ( verbose ) { out.println( "Relationship " + getDisplayName( getServer(), session, relationship, true, false ) + " created" ); } if ( parser.options().containsKey( "cd" ) ) cdTo( session, node ); return Continuation.INPUT_COMPLETE; } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_Mkrel.java
1,653
@Service.Implementation( App.class ) public class Mknode extends TransactionProvidingApp { { addOptionDefinition( "np", new OptionDefinition( OptionValueType.MUST, "Properties (a json map) to set for the new node (if one is created)" ) ); addOptionDefinition( "cd", new OptionDefinition( OptionValueType.NONE, "Go to the created node, like doing 'cd'" ) ); addOptionDefinition( "v", new OptionDefinition( OptionValueType.NONE, "Verbose mode: display created node" ) ); addOptionDefinition( "l", new OptionDefinition( OptionValueType.MUST, "Labels to attach to the created node, either a single label or a JSON array" ) ); } @Override public String getDescription() { return "Creates a new node, f.ex:\n" + "mknode --cd --np \"{'name':'Neo'}\" -l PERSON"; } @Override protected Continuation exec( AppCommandParser parser, Session session, Output out ) throws Exception { GraphDatabaseAPI db = getServer().getDb(); Node node = db.createNode( parseLabels( parser ) ); setProperties( node, parser.option( "np", null ) ); if ( parser.options().containsKey( "cd" ) ) cdTo( session, node ); if ( parser.options().containsKey( "v" ) ) { out.println( "Node " + getDisplayName( getServer(), session, node, false ) + " created" ); } return Continuation.INPUT_COMPLETE; } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_Mknode.java
1,654
private static class LimitPerTypeFilter implements Predicate<Relationship> { private final int maxRelsPerType; private final Map<String, AtomicInteger> encounteredRelationships = new HashMap<String, AtomicInteger>(); private int typesMaxedOut = 0; private final AtomicBoolean iterationHalted; public LimitPerTypeFilter( int maxRelsPerType, Map<String, Direction> types, AtomicBoolean handBreak ) { this.maxRelsPerType = maxRelsPerType; this.iterationHalted = handBreak; for ( String type : types.keySet() ) { encounteredRelationships.put( type, new AtomicInteger() ); } } @Override public boolean accept( Relationship item ) { AtomicInteger counter = encounteredRelationships.get( item.getType().name() ); int count = counter.get(); if ( count < maxRelsPerType ) { if ( counter.incrementAndGet() == maxRelsPerType ) { counter.incrementAndGet(); if ( (++typesMaxedOut) >= encounteredRelationships.size() ) { iterationHalted.set( true ); } return true; } return true; } return false; } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_Ls.java
1,655
{ @Override protected Relationship fetchNextOrNull() { return handBreak.get() ? null : super.fetchNextOrNull(); } };
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_Ls.java
1,656
{ @Override public int compare( String item1, String item2 ) { return item1.toLowerCase().compareTo( item2.toLowerCase() ); } } );
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_Ls.java
1,657
@Service.Implementation( App.class ) public class Ls extends TransactionProvidingApp { private static final int DEFAULT_MAX_RELS_PER_TYPE_LIMIT = 10; { addOptionDefinition( "b", new OptionDefinition( OptionValueType.NONE, "Brief summary instead of full content" ) ); addOptionDefinition( "v", new OptionDefinition( OptionValueType.NONE, "Verbose mode" ) ); addOptionDefinition( "q", new OptionDefinition( OptionValueType.NONE, "Quiet mode" ) ); addOptionDefinition( "p", new OptionDefinition( OptionValueType.NONE, "Lists properties" ) ); addOptionDefinition( "r", new OptionDefinition( OptionValueType.NONE, "Lists relationships" ) ); addOptionDefinition( "f", new OptionDefinition( OptionValueType.MUST, "Filters property keys/values and relationship types. Supplied either as a single value " + "or as a JSON string where both keys and values can contain regex. " + "Starting/ending {} brackets are optional. Examples:\n" + " \"username\"\n\tproperty/relationship 'username' gets listed\n" + " \".*name:ma.*, age:''\"\n\tproperties with keys matching '.*name' and values matching 'ma.*' " + "gets listed,\n\tas well as the 'age' property. Also relationships matching '.*name' or 'age'\n\tgets listed\n" + " \"KNOWS:out,LOVES:in\"\n\toutgoing KNOWS and incoming LOVES relationships gets listed" ) ); addOptionDefinition( "i", new OptionDefinition( OptionValueType.NONE, "Filters are case-insensitive (case-sensitive by default)" ) ); addOptionDefinition( "l", new OptionDefinition( OptionValueType.NONE, "Filters matches more loosely, i.e. it's considered a match if just " + "a part of a value matches the pattern, not necessarily the whole value" ) ); addOptionDefinition( "s", new OptionDefinition( OptionValueType.NONE, "Sorts relationships by type." ) ); addOptionDefinition( "m", new OptionDefinition( OptionValueType.MAY, "Display a maximum of M relationships per type (default " + DEFAULT_MAX_RELS_PER_TYPE_LIMIT + " if no value given)" ) ); addOptionDefinition( "a", new OptionDefinition( OptionValueType.NONE, "Allows for cd:ing to a node not connected to the current node (e.g. 'absolute')" ) ); } @Override public String getDescription() { return "Lists the contents of the current node or relationship. " + "Optionally supply\n" + "node id for listing a certain node using \"ls <node-id>\""; } @Override protected Continuation exec( AppCommandParser parser, Session session, Output out ) throws ShellException, RemoteException { boolean brief = parser.options().containsKey( "b" ); boolean verbose = parser.options().containsKey( "v" ); boolean quiet = parser.options().containsKey( "q" ); if ( verbose && quiet ) { verbose = false; quiet = false; } boolean displayProperties = parser.options().containsKey( "p" ); boolean displayRelationships = parser.options().containsKey( "r" ); boolean caseInsensitiveFilters = parser.options().containsKey( "i" ); boolean looseFilters = parser.options().containsKey( "l" ); Map<String, Object> filterMap = parseFilter( parser.options().get( "f" ), out ); if ( !displayProperties && !displayRelationships ) { displayProperties = true; displayRelationships = true; } NodeOrRelationship thing = null; if ( parser.arguments().isEmpty() ) { thing = this.getCurrent( session ); } else { thing = NodeOrRelationship.wrap( this.getNodeById( Long .parseLong( parser.arguments().get( 0 ) ) ) ); } if ( displayProperties ) { displayLabels( thing, out, filterMap, caseInsensitiveFilters, looseFilters, brief ); displayProperties( thing, out, verbose, quiet, filterMap, caseInsensitiveFilters, looseFilters, brief ); } if ( displayRelationships ) { if ( thing.isNode() ) { displayRelationships( parser, thing, session, out, verbose, quiet, filterMap, caseInsensitiveFilters, looseFilters, brief ); } else { displayNodes( parser, thing, session, out ); } } return Continuation.INPUT_COMPLETE; } private void displayNodes( AppCommandParser parser, NodeOrRelationship thing, Session session, Output out ) throws RemoteException, ShellException { Relationship rel = thing.asRelationship(); out.println( getDisplayName( getServer(), session, rel.getStartNode(), false ) + " --" + getDisplayName( getServer(), session, rel, true, false ) + "-> " + getDisplayName( getServer(), session, rel.getEndNode(), false ) ); } private Iterable<String> sortKeys( Iterable<String> source ) { List<String> list = new ArrayList<String>(); for ( String item : source ) { list.add( item ); } Collections.sort( list, new Comparator<String>() { @Override public int compare( String item1, String item2 ) { return item1.toLowerCase().compareTo( item2.toLowerCase() ); } } ); return list; } private void displayProperties( NodeOrRelationship thing, Output out, boolean verbose, boolean quiet, Map<String, Object> filterMap, boolean caseInsensitiveFilters, boolean looseFilters, boolean brief ) throws RemoteException { ColumnPrinter columnPrinter = quiet ? new ColumnPrinter( "*" ) : new ColumnPrinter( "*", "=" ); int count = 0; for ( String key : sortKeys( thing.getPropertyKeys() ) ) { Object value = thing.getProperty( key ); if ( !filterMatches( filterMap, caseInsensitiveFilters, looseFilters, key, value ) ) { continue; } count++; if ( !brief ) { if ( quiet ) { columnPrinter.add( key ); } else { columnPrinter.add( key, verbose ? format( value, true ) + " (" + getNiceType( value ) + ")" : format( value, true ) ); } } } columnPrinter.print( out ); if ( brief ) { out.println( "Property count: " + count ); } } private void displayLabels( NodeOrRelationship thing, Output out, Map<String, Object> filterMap, boolean caseInsensitiveFilters, boolean looseFilters, boolean brief ) throws RemoteException { List<String> labelNames = new ArrayList<String>(); for ( Label label : thing.asNode().getLabels() ) labelNames.add( label.name() ); if ( brief ) { out.println( "Label count: " + labelNames.size() ); } else { for ( String label : sortKeys( labelNames ) ) { if ( filterMatches( filterMap, caseInsensitiveFilters, looseFilters, label, "" ) ) out.println( ":" + label ); } } } private void displayRelationships( AppCommandParser parser, NodeOrRelationship thing, Session session, Output out, boolean verbose, boolean quiet, Map<String, Object> filterMap, boolean caseInsensitiveFilters, boolean looseFilters, boolean brief ) throws ShellException, RemoteException { boolean sortByType = parser.options().containsKey( "s" ); Node node = thing.asNode(); Iterable<Relationship> relationships = getRelationships( node, filterMap, caseInsensitiveFilters, looseFilters, sortByType|brief ); if ( brief ) { Iterator<Relationship> iterator = relationships.iterator(); if ( !iterator.hasNext() ) { return; } Relationship sampleRelationship = iterator.next(); RelationshipType lastType = sampleRelationship.getType(); int currentCounter = 1; while ( iterator.hasNext() ) { Relationship rel = iterator.next(); if ( !rel.isType( lastType ) ) { displayBriefRelationships( thing, session, out, sampleRelationship, currentCounter ); sampleRelationship = rel; lastType = sampleRelationship.getType(); currentCounter = 1; } else { currentCounter++; } } displayBriefRelationships( thing, session, out, sampleRelationship, currentCounter ); } else { Iterator<Relationship> iterator = relationships.iterator(); if ( parser.options().containsKey( "m" ) ) { iterator = wrapInLimitingIterator( parser, iterator, filterMap, caseInsensitiveFilters, looseFilters ); } while ( iterator.hasNext() ) { Relationship rel = iterator.next(); StringBuffer buf = new StringBuffer( getDisplayName( getServer(), session, thing, true ) ); String relDisplay = quiet ? "" : getDisplayName( getServer(), session, rel, verbose, true ); buf.append( withArrows( rel, relDisplay, thing.asNode() ) ); buf.append( getDisplayName( getServer(), session, rel.getOtherNode( node ), true ) ); out.println( buf ); } } } private Iterator<Relationship> wrapInLimitingIterator( AppCommandParser parser, Iterator<Relationship> iterator, Map<String, Object> filterMap, boolean caseInsensitiveFilters, boolean looseFilters ) throws ShellException { final AtomicBoolean handBreak = new AtomicBoolean(); int maxRelsPerType = parser.optionAsNumber( "m", DEFAULT_MAX_RELS_PER_TYPE_LIMIT ).intValue(); Map<String, Direction> types = filterMapToTypes( getServer().getDb(), Direction.BOTH, filterMap, caseInsensitiveFilters, looseFilters ); return new FilteringIterator<Relationship>( iterator, new LimitPerTypeFilter( maxRelsPerType, types, handBreak ) ) { @Override protected Relationship fetchNextOrNull() { return handBreak.get() ? null : super.fetchNextOrNull(); } }; } private static class LimitPerTypeFilter implements Predicate<Relationship> { private final int maxRelsPerType; private final Map<String, AtomicInteger> encounteredRelationships = new HashMap<String, AtomicInteger>(); private int typesMaxedOut = 0; private final AtomicBoolean iterationHalted; public LimitPerTypeFilter( int maxRelsPerType, Map<String, Direction> types, AtomicBoolean handBreak ) { this.maxRelsPerType = maxRelsPerType; this.iterationHalted = handBreak; for ( String type : types.keySet() ) { encounteredRelationships.put( type, new AtomicInteger() ); } } @Override public boolean accept( Relationship item ) { AtomicInteger counter = encounteredRelationships.get( item.getType().name() ); int count = counter.get(); if ( count < maxRelsPerType ) { if ( counter.incrementAndGet() == maxRelsPerType ) { counter.incrementAndGet(); if ( (++typesMaxedOut) >= encounteredRelationships.size() ) { iterationHalted.set( true ); } return true; } return true; } return false; } } private Iterable<Relationship> getRelationships( final Node node, Map<String, Object> filterMap, boolean caseInsensitiveFilters, boolean looseFilters, boolean sortByType ) throws ShellException { if ( sortByType ) { Path nodeAsPath = new SingleNodePath( node ); return toSortedExpander( getServer().getDb(), Direction.BOTH, filterMap, caseInsensitiveFilters, looseFilters ).expand( nodeAsPath, BranchState.NO_STATE ); } else { if ( filterMap.isEmpty() ) { return node.getRelationships(); } else { Path nodeAsPath = new SingleNodePath( node ); return toExpander( getServer().getDb(), Direction.BOTH, filterMap, caseInsensitiveFilters, looseFilters ).expand( nodeAsPath, BranchState.NO_STATE ); } } } private void displayBriefRelationships( NodeOrRelationship thing, Session session, Output out, Relationship sampleRelationship, int count ) throws ShellException, RemoteException { String relDisplay = withArrows( sampleRelationship, getDisplayName( getServer(), session, sampleRelationship, false, true ), thing.asNode() ); out.println( getDisplayName( getServer(), session, thing, true ) + relDisplay + " x" + count ); } private static String getNiceType( Object value ) { return Set.getValueTypeName( value.getClass() ); } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_Ls.java
1,658
@Service.Implementation( App.class ) public class Jsh extends TransactionProvidingApp { private App sh = new org.neo4j.shell.apps.extra.Jsh(); @Override public String getDescription() { return this.sh.getDescription(); } @Override public String getDescription( String option ) { return this.sh.getDescription( option ); } @Override protected Continuation exec( AppCommandParser parser, Session session, Output out ) throws Exception { return sh.execute( parser, session, out ); } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_Jsh.java
1,659
@Service.Implementation( App.class ) public class IndexProviderShellApp extends TransactionProvidingApp { { addOptionDefinition( "g", new OptionDefinition( OptionValueType.NONE, "Get entities for the given key and value" ) ); addOptionDefinition( "q", new OptionDefinition( OptionValueType.NONE, "Get entities for the given query" ) ); addOptionDefinition( "i", new OptionDefinition( OptionValueType.NONE, "Index the current entity with a key and (optionally) value. " + "If no value is given the property value for the key is " + "used" ) ); addOptionDefinition( "r", new OptionDefinition( OptionValueType.NONE, "Removes a key-value pair for the current entity from the index. " + "Key and value are optional" ) ); addOptionDefinition( "c", OPTION_DEF_FOR_C ); addOptionDefinition( "cd", new OptionDefinition( OptionValueType.NONE, "Does a 'cd' command to the returned node. " + "Could also be done using the -c option. (Implies -g)" ) ); addOptionDefinition( "ls", new OptionDefinition( OptionValueType.NONE, "Does a 'ls' command on the returned entities. " + "Could also be done using the -c option. (Implies -g)" ) ); addOptionDefinition( "create", new OptionDefinition( OptionValueType.NONE, "Creates a new index with a set of configuration parameters" ) ); addOptionDefinition( "get-config", new OptionDefinition( OptionValueType.NONE, "Displays the configuration for an index" ) ); addOptionDefinition( "set-config", new OptionDefinition( OptionValueType.NONE, "EXPERT, USE WITH CARE: Set one configuration parameter for an index (remove if no value)" ) ); addOptionDefinition( "t", new OptionDefinition( OptionValueType.MUST, "The type of index, either Node or Relationship" ) ); addOptionDefinition( "indexes", new OptionDefinition( OptionValueType.NONE, "Lists all index names" ) ); addOptionDefinition( "delete", new OptionDefinition( OptionValueType.NONE, "Deletes an index" ) ); } @Override public String getName() { return "index"; } @Override public String getDescription() { return "Access the legacy indexes for your Neo4j graph database. " + "Use -g for getting nodes, -i and -r to manipulate.\nExamples:\n" + "$ index -i persons name (will index property 'name' with its value for current node in the 'persons' index)\n" + "$ index -g persons name \"Thomas A. Anderson\" (will get nodes matching that name from the 'persons' index)\n" + "$ index -q persons \"name:'Thomas*'\" (will get nodes with names that start with Thomas)\n" + "$ index --cd persons name \"Agent Smith\" (will 'cd' to the 'Agent Smith' node from the 'persons' index).\n\n" + "EXPERT, USE WITH CARE. NOTE THAT INDEX DATA MAY BECOME INVALID AFTER CONFIGURATION CHANGES:\n" + "$ index --set-config accounts type fulltext (will set parameter 'type'='fulltext' for 'accounts' index).\n" + "$ index --set-config accounts to_lower_case (will remove parameter 'to_lower_case' from 'accounts' index).\n" + "$ index -t Relationship --delete friends (will delete the 'friends' relationship index)."; } @Override protected Continuation exec( AppCommandParser parser, Session session, Output out ) throws ShellException, RemoteException { boolean doCd = parser.options().containsKey( "cd" ); boolean doLs = parser.options().containsKey( "ls" ); boolean query = parser.options().containsKey( "q" ); boolean get = parser.options().containsKey( "g" ) || query || doCd || doLs; boolean index = parser.options().containsKey( "i" ); boolean remove = parser.options().containsKey( "r" ); boolean getConfig = parser.options().containsKey( "get-config" ); boolean create = parser.options().containsKey( "create" ); boolean setConfig = parser.options().containsKey( "set-config" ); boolean delete = parser.options().containsKey( "delete" ); boolean indexes = parser.options().containsKey( "indexes" ); int count = boolCount( get, index, remove, getConfig, create, setConfig, delete, indexes ); if ( count != 1 ) { throw new ShellException( "Supply one of: -g, -i, -r, --get-config, --set-config, --create, --delete, --indexes" ); } if ( get ) { String commandToRun = parser.options().get( "c" ); Collection<String> commandsToRun = new ArrayList<String>(); boolean specialCommand = false; if ( doCd || doLs ) { specialCommand = true; if ( doCd ) { commandsToRun.add( "cd -a $i" ); } else if ( doLs ) { commandsToRun.add( "ls $i" ); } } else if ( commandToRun != null ) { commandsToRun.addAll( Arrays.asList( commandToRun.split( Pattern.quote( "&&" ) ) ) ); } if ( getIndex( getIndexName( parser ), getEntityType( parser ), out ) == null ) { return Continuation.INPUT_COMPLETE; } IndexHits<PropertyContainer> result = query ? query( parser, out ) : get( parser, out ); try { for ( PropertyContainer hit : result ) { printAndInterpretTemplateLines( commandsToRun, false, !specialCommand, NodeOrRelationship.wrap( hit ), getServer(), session, out ); } } finally { result.close(); } } else if ( index ) { index( parser, session, out ); } else if ( remove ) { if ( getIndex( getIndexName( parser ), Node.class, out ) == null ) { return null; } remove( parser, session, out ); } else if ( getConfig ) { displayConfig( parser, out ); } else if ( create ) { createIndex( parser, out ); } else if ( setConfig ) { setConfig( parser, out ); } else if ( delete ) { deleteIndex( parser, out ); } if ( indexes ) { listIndexes( out ); } return Continuation.INPUT_COMPLETE; } private String getIndexName( AppCommandParser parser ) throws ShellException { return parser.argument( 0, "Index name not supplied" ); } private void listIndexes( Output out ) throws RemoteException { out.println( "Node indexes:" ); for ( String name : getServer().getDb().index().nodeIndexNames() ) { out.println( " " + name ); } out.println( "" ); out.println( "Relationship indexes:" ); for ( String name : getServer().getDb().index().relationshipIndexNames() ) { out.println( " " + name ); } } private void deleteIndex( AppCommandParser parser, Output out ) throws RemoteException, ShellException { Index<? extends PropertyContainer> index = getIndex( getIndexName( parser ), getEntityType( parser ), out ); if ( index != null ) { index.delete(); } } private void setConfig( AppCommandParser parser, Output out ) throws ShellException, RemoteException { String indexName = getIndexName( parser ); String key = parser.argument( 1, "Key not supplied" ); String value = parser.arguments().size() > 2 ? parser.arguments().get( 2 ) : null; Class<? extends PropertyContainer> entityType = getEntityType( parser ); Index<? extends PropertyContainer> index = getIndex( indexName, entityType, out ); if ( index == null ) { return; } String oldValue = value != null ? getServer().getDb().index().setConfiguration( index, key, value ) : getServer().getDb().index().removeConfiguration( index, key ); printWarning( out ); } private void printWarning( Output out ) throws RemoteException { out.println( "INDEX CONFIGURATION CHANGED, INDEX DATA MAY BE INVALID" ); } private void createIndex( AppCommandParser parser, Output out ) throws RemoteException, ShellException { String indexName = getIndexName( parser ); Class<? extends PropertyContainer> entityType = getEntityType( parser ); if ( getIndex( indexName, entityType, null ) != null ) { out.println( entityType.getClass().getSimpleName() + " index '" + indexName + "' already exists" ); return; } Map config; try { config = parser.arguments().size() >= 2 ? parseJSONMap( parser.arguments().get( 1 ) ) : null; } catch ( JSONException e ) { throw ShellException.wrapCause( e ); } if ( entityType.equals( Node.class ) ) { Index<Node> index = config != null ? getServer().getDb().index().forNodes( indexName, config ) : getServer().getDb().index().forNodes( indexName ); } else { Index<Relationship> index = config != null ? getServer().getDb().index().forRelationships( indexName, config ) : getServer().getDb().index().forRelationships( indexName ); } } private <T extends PropertyContainer> Index<T> getIndex( String indexName, Class<T> type, Output out ) throws RemoteException { IndexManager index = getServer().getDb().index(); boolean exists = (type.equals( Node.class ) && index.existsForNodes( indexName )) || (type.equals( Relationship.class ) && index.existsForRelationships( indexName )); if ( !exists ) { if ( out != null ) { out.println( "No such " + type.getSimpleName().toLowerCase() + " index '" + indexName + "'" ); } return null; } return (Index<T>) (type.equals( Node.class ) ? index.forNodes( indexName ) : index.forRelationships( indexName )); } private void displayConfig( AppCommandParser parser, Output out ) throws RemoteException, ShellException { String indexName = getIndexName( parser ); Index<? extends PropertyContainer> index = getIndex( indexName, getEntityType( parser ), out ); if ( index == null ) { return; } try { out.println( new JSONObject( getServer().getDb().index().getConfiguration( index ) ).toString( 4 ) ); } catch ( JSONException e ) { throw ShellException.wrapCause( e ); } } private Class<? extends PropertyContainer> getEntityType( AppCommandParser parser ) throws ShellException { String type = parser.options().get( "t" ); type = type != null ? type.toLowerCase() : null; if ( type == null || type.equals( "node" ) ) { return Node.class; } else if ( type.equals( "relationship" ) ) { return Relationship.class; } throw new ShellException( "'type' expects one of [Node, Relationship]" ); } private int boolCount( boolean... bools ) { int count = 0; for ( boolean bool : bools ) { if ( bool ) { count++; } } return count; } private IndexHits<PropertyContainer> get( AppCommandParser parser, Output out ) throws ShellException, RemoteException { String index = getIndexName( parser ); String key = parser.argument( 1, "Key not supplied" ); String value = parser.argument( 2, "Value not supplied" ); Index theIndex = getIndex( index, getEntityType( parser ), out ); return theIndex.get( key, value ); } private IndexHits<PropertyContainer> query( AppCommandParser parser, Output out ) throws RemoteException, ShellException { String index = getIndexName( parser ); String query1 = parser.argument( 1, "Key not supplied" ); String query2 = parser.argumentWithDefault( 2, null ); Index theIndex = getIndex( index, getEntityType( parser ), out ); return query2 != null ? theIndex.query( query1, query2 ) : theIndex.query( query1 ); } private void index( AppCommandParser parser, Session session, Output out ) throws ShellException, RemoteException { NodeOrRelationship current = getCurrent( session ); String index = getIndexName( parser ); String key = parser.argument( 1, "Key not supplied" ); Object value = parser.arguments().size() > 2 ? parser.arguments().get( 2 ) : current.getProperty( key, null ); if ( value == null ) { throw new ShellException( "No value to index" ); } Index theIndex = current.isNode() ? getServer().getDb().index().forNodes( index ) : getServer().getDb().index().forRelationships( index ); theIndex.add( current.asPropertyContainer(), key, value ); } private void remove( AppCommandParser parser, Session session, Output out ) throws ShellException, RemoteException { NodeOrRelationship current = getCurrent( session ); String index = getIndexName( parser ); String key = parser.argumentWithDefault( 1, null ); Object value = null; if ( key != null ) { value = parser.argumentWithDefault( 2, null ); } Index theIndex = getIndex( index, current.isNode() ? Node.class : Relationship.class, out ); if ( theIndex != null ) { if ( key != null && value != null ) { theIndex.remove( current.asPropertyContainer(), key, value ); } else if ( key != null ) { theIndex.remove( current.asPropertyContainer(), key ); } else { theIndex.remove( current.asPropertyContainer() ); } } } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_IndexProviderShellApp.java
1,660
@Service.Implementation( App.class ) public class Gsh extends TransactionProvidingApp { private App sh = new org.neo4j.shell.apps.extra.Gsh(); @Override public String getDescription() { return this.sh.getDescription(); } @Override public String getDescription( String option ) { return this.sh.getDescription( option ); } @Override protected Continuation exec( AppCommandParser parser, Session session, Output out ) throws Exception { return sh.execute( parser, session, out ); } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_Gsh.java
1,661
public class Schema extends TransactionProvidingApp { private static final Function<IndexDefinition, String> LABEL_COMPARE_FUNCTION = new Function<IndexDefinition, String>() { @Override public String apply( IndexDefinition index ) { return index.getLabel().name(); } }; { addOptionDefinition( "l", new OptionDefinition( OptionValueType.MUST, "Specifies which label selected operation is about" ) ); addOptionDefinition( "p", new OptionDefinition( OptionValueType.MUST, "Specifies which property selected operation is about" ) ); addOptionDefinition( "v", new OptionDefinition( OptionValueType.NONE, "Verbose output of failure descriptions etc." ) ); } @Override public String getDescription() { return "Accesses db schema. Usage: schema <action> <options...>\n" + "Listing indexes\n" + " schema ls\n" + " schema ls -l :Person\n" + "Awaiting indexes to come online\n" + " schema await -l Person -p name"; } @Override protected Continuation exec( AppCommandParser parser, Session session, Output out ) throws Exception { String action = parser.argumentWithDefault( 0, "ls" ); org.neo4j.graphdb.schema.Schema schema = getServer().getDb().schema(); Label[] labels = parseLabels( parser ); String property = parser.option( "p", null ); boolean verbose = parser.options().containsKey( "v" ); if ( action.equals( "await" ) ) { awaitIndexes( out, schema, labels, property ); } else if ( action.equals( "ls" ) ) { listIndexesAndConstraints( out, schema, labels, property, verbose ); } else { out.println( "Unknown action: " + action + "\nUSAGE:\n" + getDescription() ); } return INPUT_COMPLETE; } private void awaitIndexes( Output out, org.neo4j.graphdb.schema.Schema schema, Label[] labels, String property ) throws RemoteException { for ( IndexDefinition index : indexesByLabelAndProperty( schema, labels, property ) ) { if ( schema.getIndexState( index ) != IndexState.ONLINE ) { out.println( String.format( "Awaiting :%s ON %s %s", index.getLabel().name(), toList( index.getPropertyKeys() ), IndexState.ONLINE ) ); schema.awaitIndexOnline( index, 10000, TimeUnit.DAYS ); } } } private void listIndexesAndConstraints( Output out, org.neo4j.graphdb.schema.Schema schema, Label[] labels, final String property, boolean verbose ) throws RemoteException { reportIndexes( out, schema, labels, property, verbose ); reportConstraints( out, schema, labels, property ); } private void reportConstraints( Output out, org.neo4j.graphdb.schema.Schema schema, Label[] labels, String property ) throws RemoteException { int j = 0; for ( ConstraintDefinition constraint : constraintsByLabelAndProperty( schema, labels, property ) ) { if ( j == 0 ) { out.println(); out.println( "Constraints" ); } String labelName = constraint.getLabel().name(); out.println( String.format( " ON (%s:%s) ASSERT %s", labelName.toLowerCase(), labelName, constraint.toString() ) ); j++; } if ( j == 0 ) { out.println(); out.println( "No constraints" ); } } private void reportIndexes( Output out, org.neo4j.graphdb.schema.Schema schema, Label[] labels, String property, boolean verbose ) throws RemoteException { ColumnPrinter printer = new ColumnPrinter( " ON ", "", "" ); Iterable<IndexDefinition> indexes = indexesByLabelAndProperty( schema, labels, property ); int i = 0; for ( IndexDefinition index : sort( indexes, LABEL_COMPARE_FUNCTION ) ) { if ( i == 0 ) { out.println( "Indexes" ); } String labelAndProperties = String.format( ":%s(%s)", index.getLabel().name(), commaSeparate( index .getPropertyKeys() ) ); IndexState state = schema.getIndexState( index ); String uniqueOrNot = index.isConstraintIndex() ? "(for uniqueness constraint)" : ""; printer.add( labelAndProperties, state, uniqueOrNot ); if ( verbose && state == IndexState.FAILED ) { printer.addRaw( schema.getIndexFailure( index ) ); } i++; } if ( i == 0 ) { out.println( "No indexes" ); } else { printer.print( out ); } } private String commaSeparate( Iterable<String> keys ) { StringBuilder builder = new StringBuilder(); boolean first = true; for ( String key : keys ) { if ( !first ) { builder.append( ", " ); } else { first = false; } builder.append( key ); } return builder.toString(); } private Iterable<IndexDefinition> indexesByLabelAndProperty( org.neo4j.graphdb.schema.Schema schema, Label[] labels, final String property ) { Iterable<IndexDefinition> indexes = indexesByLabel( schema, labels ); if ( property != null ) { indexes = filter( new Predicate<IndexDefinition>() { @Override public boolean accept( IndexDefinition index ) { return indexOf( property, index.getPropertyKeys() ) != -1; } }, indexes ); } return indexes; } private Iterable<ConstraintDefinition> constraintsByLabelAndProperty( org.neo4j.graphdb.schema.Schema schema, final Label[] labels, final String property ) { return filter( new Predicate<ConstraintDefinition>() { @Override public boolean accept( ConstraintDefinition constraint ) { return hasLabel( constraint, labels ) && isMatchingConstraint( constraint, property ); } }, schema.getConstraints() ); } private boolean hasLabel( ConstraintDefinition constraint, Label[] labels ) { if ( labels.length == 0 ) { return true; } for ( Label label : labels ) { if ( constraint.getLabel().name().equals( label.name() ) ) { return true; } } return false; } private boolean isMatchingConstraint( ConstraintDefinition constraint, final String property ) { if ( property == null ) { return true; } return indexOf( property, constraint.getPropertyKeys() ) != -1; } private Iterable<IndexDefinition> indexesByLabel( org.neo4j.graphdb.schema.Schema schema, Label[] labels ) { Iterable<IndexDefinition> indexes = schema.getIndexes(); for ( final Label label : labels ) { indexes = filter( new Predicate<IndexDefinition>() { @Override public boolean accept( IndexDefinition item ) { return item.getLabel().name().equals( label.name() ); } }, indexes ); } return indexes; } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_Schema.java
1,662
{ @Override public boolean accept( IndexDefinition index ) { return indexOf( property, index.getPropertyKeys() ) != -1; } }, indexes );
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_Schema.java
1,663
@Service.Implementation( App.class ) public class Profile extends Start { public Profile() { super(); } @Override public String getDescription() { return "Executes a Cypher query and prints out execution plan and other profiling information. " + "Usage: profile <query>\n" + "Example: PROFILE START me = node({self}) MATCH me-[:KNOWS]->you RETURN you.name\n" + "where {self} will be replaced with the current location in the graph"; } @Override protected Continuation exec( AppCommandParser parser, Session session, Output out ) throws ShellException, RemoteException { String query = parser.getLineWithoutApp(); if ( isComplete( query ) ) { ExecutionEngine engine = new ExecutionEngine( getServer().getDb(), getCypherLogger() ); try { ExecutionResult result = engine.profile( query, getParameters( session ) ); out.println( result.dumpToString() ); out.println( result.executionPlanDescription().toString() ); } catch ( CypherException e ) { throw ShellException.wrapCause( e ); } return Continuation.INPUT_COMPLETE; } else { return Continuation.INPUT_INCOMPLETE; } } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_cypher_Profile.java
1,664
{ @Override public boolean accept( ConstraintDefinition constraint ) { return hasLabel( constraint, labels ) && isMatchingConstraint( constraint, property ); } }, schema.getConstraints() );
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_Schema.java
1,665
@Service.Implementation( App.class ) public class Optional extends Start { }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_cypher_Optional.java
1,666
@Service.Implementation( App.class ) public class Merge extends Start { }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_cypher_Merge.java
1,667
@Service.Implementation( App.class ) public class Match extends Start { }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_cypher_Match.java
1,668
@Service.Implementation( App.class ) public class Load extends Start { }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_cypher_Load.java
1,669
public class Exporter { private final SubGraphExporter exporter; Exporter(SubGraph graph) { exporter = new SubGraphExporter( graph ); } public void export( Output out ) throws RemoteException, ShellException { begin( out ); exporter.export(asWriter(out)); out.println(";"); commit(out); } private PrintWriter asWriter(Output out) { return new PrintWriter( new OutputAsWriter( out ) ); } private void begin( Output out ) throws RemoteException { out.println( "begin" ); } private void commit( Output out ) throws RemoteException { out.println( "commit" ); } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_cypher_Exporter.java
1,670
@Service.Implementation( App.class ) public class Dump extends Start { @Override public String getDescription() { return "Executes a Cypher query to export a subgraph. Usage: DUMP start <rest of query>;\n" + "Example: DUMP start n = node({self}) MATCH n-[r]->m RETURN n,r,m;\n" + "where {self} will be replaced with the current location in the graph." + "Please, note that the query must end with a semicolon. Other parameters are\n" + "taken from shell variables, see 'help export'."; } @Override protected Continuation exec( AppCommandParser parser, Session session, Output out ) throws ShellException, RemoteException { if ( parser.arguments().isEmpty() ) { final SubGraph graph = DatabaseSubGraph.from(getServer().getDb()); export( graph, out); return Continuation.INPUT_COMPLETE; } AppCommandParser newParser = newParser( parser ); return super.exec( newParser, session, out ); } private AppCommandParser newParser(AppCommandParser parser) throws ShellException { String newLine = parser.getLineWithoutApp(); AppCommandParser newParser = newParser( newLine ); newParser.options().putAll( parser.options() ); return newParser; } private AppCommandParser newParser( final String line ) throws ShellException { try { return new AppCommandParser( getServer(), line ); } catch ( Exception e ) { throw launderedException( ShellException.class, "Error parsing input " + line, e ); } } private void export(SubGraph subGraph, Output out) throws RemoteException, ShellException { new Exporter( subGraph ).export( out ); } @Override protected void handleResult( Output out, ExecutionResult result, long startTime, Session session, AppCommandParser parser ) throws RemoteException, ShellException { final SubGraph subGraph = CypherResultSubGraph.from(result, getServer().getDb(), false); export( subGraph, out); } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_cypher_Dump.java
1,671
@Service.Implementation( App.class ) public class Drop extends Start { }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_cypher_Drop.java
1,672
@Service.Implementation( App.class ) public class Cypher extends Start { @Override public String getDescription() { return "Executes a Cypher query with an older parser. " + "Usage: cypher <version> start <rest of query>\n" + "Example: CYPHER 1.5 START me = node({self}) MATCH me-[:KNOWS]->you RETURN you.name\n" + "where {self} will be replaced with the current location in the graph"; } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_cypher_Cypher.java
1,673
@Service.Implementation( App.class ) public class Create extends Start { }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_cypher_Create.java
1,674
class TypedId { private final String type; private final long id; private final boolean isNode; /** * @param typedId the serialized string. */ public TypedId( String typedId ) { this( typedId.substring( 0, 1 ), Long.parseLong( typedId.substring( 1 ) ) ); } /** * @param type the type * @param id the object's id. */ public TypedId( String type, long id ) { this.type = type; this.id = id; this.isNode = type.equals( NodeOrRelationship.TYPE_NODE ); } /** * @return the type. */ public String getType() { return this.type; } /** * @return the object's id. */ public long getId() { return this.id; } /** * @return whether or not the type is a {@link Node}. */ public boolean isNode() { return this.isNode; } /** * @return whether or not the type is a {@link Relationship}. */ public boolean isRelationship() { return !this.isNode; } @Override public boolean equals( Object o ) { if ( !( o instanceof TypedId ) ) { return false; } TypedId other = ( TypedId ) o; return this.type.equals( other.type ) && this.id == other.id; } @Override public int hashCode() { int code = 7; code = 31 * code + new Long( this.id ).hashCode(); code = 31 * code + this.type.hashCode(); return code; } @Override public String toString() { return this.type + this.id; } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_TypedId.java
1,675
private class CompiledScriptEvaluator implements Evaluator { private final Object compiledScript; private final Object context; CompiledScriptEvaluator( Object compiledScript ) throws Exception { this.compiledScript = compiledScript; this.context = scripting.newContext(); } @Override public Evaluation evaluate( Path path ) { try { scripting.setContextAttribute( context, "position", path ); Object result = scripting.executeCompiledScript( compiledScript, context ); if ( result instanceof Boolean ) { return Evaluation.ofIncludes( (Boolean) result ); } else if ( result instanceof Evaluation ) { return (Evaluation) result; } throw new IllegalArgumentException( "Cannot return value " + result + " from an evaluator" ); } catch ( Exception e ) { if ( e instanceof RuntimeException ) { throw (RuntimeException) e; } throw new RuntimeException( e ); } } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_Trav.java
1,676
@Service.Implementation( App.class ) public class Trav extends TransactionProvidingApp { private ScriptEngineViaReflection scripting; /** * Constructs a new command which can traverse the graph. */ public Trav() { this.addOptionDefinition( "o", new OptionDefinition( OptionValueType.MUST, "The traversal order [BREADTH_FIRST/DEPTH_FIRST/breadth/depth]" ) ); this.addOptionDefinition( "r", new OptionDefinition( OptionValueType.MUST, "The relationship type(s) expressed as a JSON string " + "(supports regex matching of the types) f.ex. " + "\"MY_REL_TYPE:out,.*_HAS_.*:both\". Matching is case-insensitive." ) ); this.addOptionDefinition( "f", new OptionDefinition( OptionValueType.MUST, "Filters node property keys/values. Supplied either as a single " + "value or as a JSON string where both keys and values can " + "contain regex. Starting/ending {} brackets are optional. Examples:\n" + "\"username\"\n" + " nodes which has property 'username' gets listed\n" + "\".*name: ma.*, age: ''\"\n" + " nodes which has any key matching '.*name' where the " + "property value\n" + " for that key matches 'ma.*' AND has the 'age' property gets listed" ) ); this.addOptionDefinition( "i", new OptionDefinition( OptionValueType.NONE, "Filters are case-insensitive (case-sensitive by default)" ) ); this.addOptionDefinition( "l", new OptionDefinition( OptionValueType.NONE, "Filters matches more loosely, i.e. it's considered a match if " + "just a part of a value matches the pattern, not necessarily " + "the whole value" ) ); this.addOptionDefinition( "c", OPTION_DEF_FOR_C ); this.addOptionDefinition( "d", new OptionDefinition( OptionValueType.MUST, "Depth limit" ) ); this.addOptionDefinition( "e", new OptionDefinition( OptionValueType.MUST, "Custom javascript evaluator" ) ); this.addOptionDefinition( "u", new OptionDefinition( OptionValueType.MUST, "Uniqueness of the entities encountered during traversal " + niceEnumAlternatives( Uniqueness.class ) ) ); } @Override public String getDescription() { return "Traverses the graph from your current position (pwd). " + "It's a reflection of the neo4j traverser API with some options for filtering " + "which nodes will be returned."; } @Override protected Continuation exec( AppCommandParser parser, Session session, Output out ) throws ShellException, RemoteException { assertCurrentIsNode( session ); Node node = this.getCurrent( session ).asNode(); boolean caseInsensitiveFilters = parser.options().containsKey( "i" ); boolean looseFilters = parser.options().containsKey( "l" ); boolean quiet = parser.options().containsKey( "q" ); // Order TraversalDescription description = Traversal.description(); String order = parser.options().get( "o" ); if ( order != null ) { description = description.order( parseOrder( order ) ); } // Relationship types / expander String relationshipTypes = parser.options().get( "r" ); if ( relationshipTypes != null ) { Map<String, Object> types = parseFilter( relationshipTypes, out ); description = description.expand( toExpander( getServer().getDb(), null, types, caseInsensitiveFilters, looseFilters ) ); } // Uniqueness String uniqueness = parser.options().get( "u" ); if ( uniqueness != null ) { description = description.uniqueness( parseUniqueness( uniqueness ) ); } // Depth limit String depthLimit = parser.options().get( "d" ); if ( depthLimit != null ) { description = description.evaluator( toDepth( parseInt( depthLimit ) ) ); } // Custom evaluator String evaluator = parser.options().get( "e" ); if ( evaluator != null ) { description = description.evaluator( parseEvaluator( evaluator ) ); } String filterString = parser.options().get( "f" ); Map<String, Object> filterMap = filterString != null ? parseFilter( filterString, out ) : null; String commandToRun = parser.options().get( "c" ); Collection<String> commandsToRun = new ArrayList<String>(); if ( commandToRun != null ) { commandsToRun.addAll( Arrays.asList( commandToRun.split( Pattern.quote( "&&" ) ) ) ); } for ( Path path : description.traverse( node ) ) { boolean hit = false; if ( filterMap == null ) { hit = true; } else { Node endNode = path.endNode(); Map<String, Boolean> matchPerFilterKey = new HashMap<String, Boolean>(); for ( String key : endNode.getPropertyKeys() ) { for ( Map.Entry<String, Object> filterEntry : filterMap.entrySet() ) { String filterKey = filterEntry.getKey(); if ( matchPerFilterKey.containsKey( filterKey ) ) { continue; } if ( matches( newPattern( filterKey, caseInsensitiveFilters ), key, caseInsensitiveFilters, looseFilters ) ) { Object value = endNode.getProperty( key ); String filterPattern = filterEntry.getValue() != null ? filterEntry.getValue().toString() : null; if ( matches( newPattern( filterPattern, caseInsensitiveFilters ), value.toString(), caseInsensitiveFilters, looseFilters ) ) { matchPerFilterKey.put( filterKey, true ); } } } } if ( matchPerFilterKey.size() == filterMap.size() ) { hit = true; } } if ( hit ) { if ( commandsToRun.isEmpty() ) { printPath( path, quiet, session, out ); } else { printAndInterpretTemplateLines( commandsToRun, false, true, NodeOrRelationship.wrap( path.endNode() ), getServer(), session, out ); } } } return Continuation.INPUT_COMPLETE; } private Evaluator parseEvaluator( String evaluator ) throws ShellException { scripting = scripting != null ? scripting : new ScriptEngineViaReflection( getServer() ); try { evaluator = decorateWithImports( evaluator, STANDARD_EVAL_IMPORTS ); Object scriptEngine = scripting.getJavascriptEngine(); Object compiledScript = scripting.compile( scriptEngine, evaluator ); return new CompiledScriptEvaluator( compiledScript ); } catch ( Exception e ) { throw ShellException.wrapCause( e ); } } private UniquenessFactory parseUniqueness( String uniqueness ) { return parseEnum( Uniqueness.class, uniqueness, null ); } private BranchOrderingPolicy parseOrder( String order ) { if ( order.equals( "depth first" ) || "depth first".startsWith( order.toLowerCase() ) ) { return Traversal.preorderDepthFirst(); } if ( order.equals( "breadth first" ) || "breadth first".startsWith( order.toLowerCase() ) ) { return Traversal.preorderBreadthFirst(); } return (BranchOrderingPolicy) parseEnum( CommonBranchOrdering.class, order, null ); } // private class ScriptEvaluator implements Evaluator // { // private final Object scriptEngine; // private final String code; // // ScriptEvaluator( Object scriptEngine, String code ) // { // this.scriptEngine = scriptEngine; // this.code = code; // } // // @Override // public Evaluation evaluate( Path path ) // { // try // { // System.out.println( "interpreting " + code ); // Object result = scripting.interpret( scriptEngine, code ); // if ( result instanceof Boolean ) // { // return Evaluation.ofIncludes( (Boolean) result ); // } // else if ( result instanceof Evaluation ) // { // return (Evaluation) result; // } // throw new IllegalArgumentException( "Cannot return value " + result + " from an evaluator" ); // } // catch ( Exception e ) // { // if ( e instanceof RuntimeException ) // { // throw (RuntimeException) e; // } // throw new RuntimeException( e ); // } // } // } private class CompiledScriptEvaluator implements Evaluator { private final Object compiledScript; private final Object context; CompiledScriptEvaluator( Object compiledScript ) throws Exception { this.compiledScript = compiledScript; this.context = scripting.newContext(); } @Override public Evaluation evaluate( Path path ) { try { scripting.setContextAttribute( context, "position", path ); Object result = scripting.executeCompiledScript( compiledScript, context ); if ( result instanceof Boolean ) { return Evaluation.ofIncludes( (Boolean) result ); } else if ( result instanceof Evaluation ) { return (Evaluation) result; } throw new IllegalArgumentException( "Cannot return value " + result + " from an evaluator" ); } catch ( Exception e ) { if ( e instanceof RuntimeException ) { throw (RuntimeException) e; } throw new RuntimeException( e ); } } } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_Trav.java
1,677
{ @Override public PathExpander reverse() { return this; } @Override public Iterable<Relationship> expand( Path path, BranchState state ) { return Collections.emptyList(); } };
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_TransactionProvidingApp.java
1,678
public abstract class TransactionProvidingApp extends AbstractApp { private static final Label[] EMPTY_LABELS = new Label[0]; protected static final String[] STANDARD_EVAL_IMPORTS = new String[] { "org.neo4j.graphdb", "org.neo4j.graphdb.event", "org.neo4j.graphdb.index", "org.neo4j.graphdb.traversal", "org.neo4j.kernel" }; protected static final OptionDefinition OPTION_DEF_FOR_C = new OptionDefinition( OptionValueType.MUST, "Command to run for each returned node. Use $i for node/relationship id, example:\n" + "-c \"ls -f name $i\". Multiple commands can be supplied with && in between" ); /** * @param server the {@link GraphDatabaseShellServer} to get the current * node/relationship from. * @param session the {@link Session} used by the client. * @return the current node/relationship the client stands on * at the moment. * @throws ShellException if some error occured. */ public static NodeOrRelationship getCurrent( GraphDatabaseShellServer server, Session session ) throws ShellException { String currentThing = session.getCurrent(); NodeOrRelationship result; /* Note: Artifact of removing the ref node, revisit and clean up */ if ( currentThing == null || currentThing.equals( "(?)" ) ) { throw new ShellException( "Not currently standing on any entity." ); } else { TypedId typedId = new TypedId( currentThing ); result = getThingById( server, typedId ); } return result; } protected NodeOrRelationship getCurrent( Session session ) throws ShellException { return getCurrent( getServer(), session ); } public static boolean isCurrent( Session session, NodeOrRelationship thing ) throws ShellException { String currentThing = session.getCurrent(); return currentThing != null && currentThing.equals( thing.getTypedId().toString() ); } protected static void clearCurrent( Session session ) { session.setCurrent( getDisplayNameForNonExistent()); } protected static void setCurrent( Session session, NodeOrRelationship current ) throws ShellException { session.setCurrent( current.getTypedId().toString() ); } protected void assertCurrentIsNode( Session session ) throws ShellException { NodeOrRelationship current = getCurrent( session ); if ( !current.isNode() ) { throw new ShellException( "You must stand on a node to be able to do this" ); } } @Override public GraphDatabaseShellServer getServer() { return ( GraphDatabaseShellServer ) super.getServer(); } protected static RelationshipType getRelationshipType( String name ) { return DynamicRelationshipType.withName( name ); } protected static Direction getDirection( String direction ) throws ShellException { return getDirection( direction, Direction.OUTGOING ); } protected static Direction getDirection( String direction, Direction defaultDirection ) throws ShellException { return parseEnum( Direction.class, direction, defaultDirection ); } protected static NodeOrRelationship getThingById( GraphDatabaseShellServer server, TypedId typedId ) throws ShellException { NodeOrRelationship result; if ( typedId.isNode() ) { try { result = NodeOrRelationship.wrap( server.getDb().getNodeById( typedId.getId() ) ); } catch ( NotFoundException e ) { throw new ShellException( "Node " + typedId.getId() + " not found" ); } } else { try { result = NodeOrRelationship.wrap( server.getDb().getRelationshipById( typedId.getId() ) ); } catch ( NotFoundException e ) { throw new ShellException( "Relationship " + typedId.getId() + " not found" ); } } return result; } protected NodeOrRelationship getThingById( TypedId typedId ) throws ShellException { return getThingById( getServer(), typedId ); } protected Node getNodeById( long id ) { return this.getServer().getDb().getNodeById( id ); } @Override public Continuation execute( AppCommandParser parser, Session session, Output out ) throws Exception { try ( Transaction tx = getServer().getDb().beginTx() ) { Continuation result = this.exec( parser, session, out ); tx.success(); return result; } } @Override public final List<String> completionCandidates( String partOfLine, Session session ) throws ShellException { try ( Transaction tx = getServer().getDb().beginTx() ) { List<String> result = completionCandidatesInTx( partOfLine, session ); tx.success(); return result; } } protected List<String> completionCandidatesInTx( String partOfLine, Session session ) throws ShellException { /* * Calls super of the non-tx version (completionCandidates). In an implementation the call hierarchy would be: * * TransactionProvidingApp.completionCandidates() * --> MyApp.completionCandidatesInTx() - calls super.completionCandidatesInTx() * --> TransactionProvidingApp.completionCandidatesInTx() * --> AbstractApp.completionCandidates() */ return super.completionCandidates( partOfLine, session ); } protected String directionAlternatives() { return "OUTGOING, INCOMING, o, i"; } protected abstract Continuation exec( AppCommandParser parser, Session session, Output out ) throws Exception; protected void printPath( Path path, boolean quietPrint, Session session, Output out ) throws RemoteException, ShellException { StringBuilder builder = new StringBuilder(); Node currentNode = null; for ( PropertyContainer entity : path ) { String display; if ( entity instanceof Relationship ) { display = quietPrint ? "" : getDisplayName( getServer(), session, (Relationship) entity, false, true ); display = withArrows( (Relationship) entity, display, currentNode ); } else { currentNode = (Node) entity; display = getDisplayName( getServer(), session, currentNode, true ); } builder.append( display ); } out.println( builder.toString() ); } protected void setProperties( PropertyContainer entity, String propertyJson ) throws ShellException { if ( propertyJson == null ) { return; } try { Map<String, Object> properties = parseJSONMap( propertyJson ); for ( Map.Entry<String, Object> entry : properties.entrySet() ) { entity.setProperty( entry.getKey(), jsonToNeo4jPropertyValue( entry.getValue() ) ); } } catch ( JSONException e ) { throw ShellException.wrapCause( e ); } } private Object jsonToNeo4jPropertyValue( Object value ) throws ShellException { try { if ( value instanceof JSONArray ) { JSONArray array = (JSONArray) value; Object firstItem = array.get( 0 ); Object resultArray = Array.newInstance( firstItem.getClass(), array.length() ); for ( int i = 0; i < array.length(); i++ ) { Array.set( resultArray, i, array.get( i ) ); } return resultArray; } return value; } catch ( JSONException e ) { throw new ShellException( stackTraceAsString( e ) ); } } protected void cdTo( Session session, Node node ) throws RemoteException, ShellException { List<TypedId> wd = readCurrentWorkingDir( session ); try { wd.add( getCurrent( session ).getTypedId() ); } catch ( ShellException e ) { // OK not found then } writeCurrentWorkingDir( wd, session ); setCurrent( session, NodeOrRelationship.wrap( node ) ); } private static String getDisplayNameForCurrent( GraphDatabaseShellServer server, Session session ) throws ShellException { NodeOrRelationship current = getCurrent( server, session ); return current.isNode() ? "(me)" : "<me>"; } public static String getDisplayNameForNonExistent() { return "(?)"; } /** * @param server the {@link GraphDatabaseShellServer} to run at. * @param session the {@link Session} used by the client. * @param thing the thing to get the name-representation for. * @return the display name for a {@link Node}. */ public static String getDisplayName( GraphDatabaseShellServer server, Session session, NodeOrRelationship thing, boolean checkForMe ) throws ShellException { if ( thing.isNode() ) { return getDisplayName( server, session, thing.asNode(), checkForMe ); } else { return getDisplayName( server, session, thing.asRelationship(), true, checkForMe ); } } /** * @param server the {@link GraphDatabaseShellServer} to run at. * @param session the {@link Session} used by the client. * @param typedId the id for the item to display. * @return a display string for the {@code typedId}. * @throws ShellException if an error occurs. */ public static String getDisplayName( GraphDatabaseShellServer server, Session session, TypedId typedId, boolean checkForMe ) throws ShellException { return getDisplayName( server, session, getThingById( server, typedId ), checkForMe ); } /** * @param server the {@link GraphDatabaseShellServer} to run at. * @param session the {@link Session} used by the client. * @param node the {@link Node} to get a display string for. * @return a display string for {@code node}. */ public static String getDisplayName( GraphDatabaseShellServer server, Session session, Node node, boolean checkForMe ) throws ShellException { if ( checkForMe && isCurrent( session, NodeOrRelationship.wrap( node ) ) ) { return getDisplayNameForCurrent( server, session ); } String title = findTitle( session, node ); StringBuilder result = new StringBuilder( "(" ); result.append( title != null ? title + "," : "" ); result.append( node.getId() ); result.append( ")" ); return result.toString(); } protected static String findTitle( Session session, Node node ) throws ShellException { String keys = session.getTitleKeys(); if ( keys == null ) { return null; } String[] titleKeys = keys.split( Pattern.quote( "," ) ); Pattern[] patterns = new Pattern[ titleKeys.length ]; for ( int i = 0; i < titleKeys.length; i++ ) { patterns[ i ] = Pattern.compile( titleKeys[ i ] ); } for ( Pattern pattern : patterns ) { for ( String nodeKey : node.getPropertyKeys() ) { if ( matches( pattern, nodeKey, false, false ) ) { return trimLength( session, format( node.getProperty( nodeKey ), false ) ); } } } return null; } private static String trimLength( Session session, String string ) throws ShellException { String maxLengthString = session.getMaxTitleLength(); int maxLength = maxLengthString != null ? Integer.parseInt( maxLengthString ) : Integer.MAX_VALUE; if ( string.length() > maxLength ) { string = string.substring( 0, maxLength ) + "..."; } return string; } /** * @param server the {@link GraphDatabaseShellServer} to run at. * @param session the {@link Session} used by the client. * @param relationship the {@link Relationship} to get a display name for. * @param verbose whether or not to include the relationship id as well. * @return a display string for the {@code relationship}. */ public static String getDisplayName( GraphDatabaseShellServer server, Session session, Relationship relationship, boolean verbose, boolean checkForMe ) throws ShellException { if ( checkForMe && isCurrent( session, NodeOrRelationship.wrap( relationship ) ) ) { return getDisplayNameForCurrent( server, session ); } StringBuilder result = new StringBuilder( "[" ); result.append( ":" ).append( relationship.getType().name() ); result.append( verbose ? "," + relationship.getId() : "" ); result.append( "]" ); return result.toString(); } public static String withArrows( Relationship relationship, String displayName, Node leftNode ) { if ( relationship.getStartNode().equals( leftNode ) ) { return "-" + displayName + "->"; } else if ( relationship.getEndNode().equals( leftNode ) ) { return "<-" + displayName + "-"; } throw new IllegalArgumentException( leftNode + " is neither start nor end node to " + relationship ); } protected static String fixCaseSensitivity( String string, boolean caseInsensitive ) { return caseInsensitive ? string.toLowerCase() : string; } protected static Pattern newPattern( String pattern, boolean caseInsensitive ) { return pattern == null ? null : Pattern.compile( fixCaseSensitivity( pattern, caseInsensitive ) ); } protected static boolean matches( Pattern patternOrNull, String value, boolean caseInsensitive, boolean loose ) { if ( patternOrNull == null ) { return true; } value = fixCaseSensitivity( value, caseInsensitive ); return loose ? patternOrNull.matcher( value ).find() : patternOrNull.matcher( value ).matches(); } protected static <T extends Enum<T>> String niceEnumAlternatives( Class<T> enumClass ) { StringBuilder builder = new StringBuilder( "[" ); int count = 0; for ( T enumConstant : enumClass.getEnumConstants() ) { builder.append( count++ == 0 ? "" : ", " ); builder.append( enumConstant.name() ); } return builder.append( "]" ).toString(); } protected static <T extends Enum<T>> T parseEnum( Class<T> enumClass, String name, T defaultValue, Pair<String, T>... additionalPairs ) { if ( name == null ) { return defaultValue; } name = name.toLowerCase(); for ( T enumConstant : enumClass.getEnumConstants() ) { if ( enumConstant.name().equalsIgnoreCase( name ) ) { return enumConstant; } } for ( T enumConstant : enumClass.getEnumConstants() ) { if ( enumConstant.name().toLowerCase().startsWith( name ) ) { return enumConstant; } } for ( Pair<String, T> additional : additionalPairs ) { if ( additional.first().equalsIgnoreCase( name ) ) { return additional.other(); } } for ( Pair<String, T> additional : additionalPairs ) { if ( additional.first().toLowerCase().startsWith( name ) ) { return additional.other(); } } throw new IllegalArgumentException( "No '" + name + "' or '" + name + ".*' in " + enumClass ); } protected static boolean filterMatches( Map<String, Object> filterMap, boolean caseInsensitiveFilters, boolean looseFilters, String key, Object value ) { if ( filterMap == null || filterMap.isEmpty() ) { return true; } for ( Map.Entry<String, Object> filter : filterMap.entrySet() ) { if ( matches( newPattern( filter.getKey(), caseInsensitiveFilters ), key, caseInsensitiveFilters, looseFilters ) ) { String filterValue = filter.getValue() != null ? filter.getValue().toString() : null; if ( matches( newPattern( filterValue, caseInsensitiveFilters ), value.toString(), caseInsensitiveFilters, looseFilters ) ) { return true; } } } return false; } protected static String frame( String string, boolean frame ) { return frame ? "[" + string + "]" : string; } protected static String format( Object value, boolean includeFraming ) { String result; if ( value.getClass().isArray() ) { StringBuilder buffer = new StringBuilder(); int length = Array.getLength( value ); for ( int i = 0; i < length; i++ ) { Object singleValue = Array.get( value, i ); if ( i > 0 ) { buffer.append( "," ); } buffer.append( frame( singleValue.toString(), includeFraming ) ); } result = buffer.toString(); } else { result = frame( value.toString(), includeFraming ); } return result; } protected static void printAndInterpretTemplateLines( Collection<String> templateLines, boolean forcePrintHitHeader, boolean newLineBetweenHits, NodeOrRelationship entity, GraphDatabaseShellServer server, Session session, Output out ) throws ShellException, RemoteException { if ( templateLines.isEmpty() || forcePrintHitHeader ) { out.println( getDisplayName( server, session, entity, true ) ); } if ( !templateLines.isEmpty() ) { Map<String, Object> data = new HashMap<String, Object>(); data.put( "i", entity.getId() ); for ( String command : templateLines ) { String line = TextUtil.templateString( command, data ); server.interpretLine( session.getId(), line, out ); } } if ( newLineBetweenHits ) { out.println(); } } /** * Reads the session variable specified in {@link org.neo4j.shell.Variables#WORKING_DIR_KEY} and * returns it as a list of typed ids. * @param session the session to read from. * @return the working directory as a list. * @throws RemoteException if an RMI error occurs. */ public static List<TypedId> readCurrentWorkingDir( Session session ) throws RemoteException { List<TypedId> list = new ArrayList<TypedId>(); String path = session.getPath(); if ( path != null && path.trim().length() > 0 ) { for ( String typedId : path.split( "," ) ) { list.add( new TypedId( typedId ) ); } } return list; } public static void writeCurrentWorkingDir( List<TypedId> paths, Session session ) throws RemoteException { String path = makePath( paths ); session.setPath( path ); } private static String makePath( List<TypedId> paths ) { StringBuilder buffer = new StringBuilder(); for ( TypedId typedId : paths ) { if ( buffer.length() > 0 ) { buffer.append( "," ); } buffer.append( typedId.toString() ); } return buffer.length() > 0 ? buffer.toString() : null; } protected static Map<String, Direction> filterMapToTypes( GraphDatabaseService db, Direction defaultDirection, Map<String, Object> filterMap, boolean caseInsensitiveFilters, boolean looseFilters ) throws ShellException { Map<String, Direction> matches = new TreeMap<String, Direction>(); for ( RelationshipType type : GlobalGraphOperations.at( db ).getAllRelationshipTypes() ) { Direction direction = null; if ( filterMap == null || filterMap.isEmpty() ) { direction = defaultDirection; } else { for ( Map.Entry<String, Object> entry : filterMap.entrySet() ) { if ( matches( newPattern( entry.getKey(), caseInsensitiveFilters ), type.name(), caseInsensitiveFilters, looseFilters ) ) { direction = getDirection( entry.getValue() != null ? entry.getValue().toString() : null, defaultDirection ); break; } } } // It matches if ( direction != null ) { matches.put( type.name(), direction ); } } return matches.isEmpty() ? Collections.<String, Direction>emptyMap() : matches; } protected static PathExpander toExpander( GraphDatabaseService db, Direction defaultDirection, Map<String, Object> relationshipTypes, boolean caseInsensitiveFilters, boolean looseFilters ) throws ShellException { defaultDirection = defaultDirection != null ? defaultDirection : Direction.BOTH; Map<String, Direction> matches = filterMapToTypes( db, defaultDirection, relationshipTypes, caseInsensitiveFilters, looseFilters ); Expander expander = Traversal.emptyExpander(); if ( matches == null ) { return EMPTY_EXPANDER; } for ( Map.Entry<String, Direction> entry : matches.entrySet() ) { expander = expander.add( DynamicRelationshipType.withName( entry.getKey() ), entry.getValue() ); } return (PathExpander) expander; } protected static PathExpander toSortedExpander( GraphDatabaseService db, Direction defaultDirection, Map<String, Object> relationshipTypes, boolean caseInsensitiveFilters, boolean looseFilters ) throws ShellException { defaultDirection = defaultDirection != null ? defaultDirection : Direction.BOTH; Map<String, Direction> matches = filterMapToTypes( db, defaultDirection, relationshipTypes, caseInsensitiveFilters, looseFilters ); Expander expander = new OrderedByTypeExpander(); for ( Map.Entry<String, Direction> entry : matches.entrySet() ) { expander = expander.add( DynamicRelationshipType.withName( entry.getKey() ), entry.getValue() ); } return (PathExpander) expander; } private static final PathExpander EMPTY_EXPANDER = new PathExpander() { @Override public PathExpander reverse() { return this; } @Override public Iterable<Relationship> expand( Path path, BranchState state ) { return Collections.emptyList(); } }; protected Label[] parseLabels( AppCommandParser parser ) { String labelValue = parser.option( "l", null ); if ( labelValue == null ) { return EMPTY_LABELS; } labelValue = labelValue.trim(); if ( labelValue.startsWith( "[" ) ) { Object[] items = parseArray( labelValue ); Label[] labels = new Label[items.length]; for ( int i = 0; i < items.length; i++ ) { labels[i] = labelWithOrWithoutColon( items[i].toString() ); } return labels; } else { return new Label[] { labelWithOrWithoutColon( labelValue ) }; } } private Label labelWithOrWithoutColon( String label ) { String labelName = label.startsWith( ":" ) ? label.substring( 1 ) : label; return DynamicLabel.label( labelName ); } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_TransactionProvidingApp.java
1,679
private static class ValueTypeContext { private final Class<?> fundamentalClass; private final Class<?> boxClass; private final Class<?> fundamentalArrayClass; private final Class<?> boxArrayClass; ValueTypeContext( Class<?> fundamentalClass, Class<?> boxClass, Class<?> fundamentalArrayClass, Class<?> boxArrayClass ) { this.fundamentalClass = fundamentalClass; this.boxClass = boxClass; this.fundamentalArrayClass = fundamentalArrayClass; this.boxArrayClass = boxArrayClass; } public String getName() { return fundamentalClass.equals( boxClass ) ? boxClass.getSimpleName() : fundamentalClass.getSimpleName(); } public String getArrayName() { return getName() + "[]"; } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_Set.java
1,680
private static class ValueType { private final ValueTypeContext context; private final boolean isArray; ValueType( ValueTypeContext context, boolean isArray ) { this.context = context; this.isArray = isArray; } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_Set.java
1,681
@Service.Implementation( App.class ) public class Set extends TransactionProvidingApp { private static class ValueTypeContext { private final Class<?> fundamentalClass; private final Class<?> boxClass; private final Class<?> fundamentalArrayClass; private final Class<?> boxArrayClass; ValueTypeContext( Class<?> fundamentalClass, Class<?> boxClass, Class<?> fundamentalArrayClass, Class<?> boxArrayClass ) { this.fundamentalClass = fundamentalClass; this.boxClass = boxClass; this.fundamentalArrayClass = fundamentalArrayClass; this.boxArrayClass = boxArrayClass; } public String getName() { return fundamentalClass.equals( boxClass ) ? boxClass.getSimpleName() : fundamentalClass.getSimpleName(); } public String getArrayName() { return getName() + "[]"; } } private static class ValueType { private final ValueTypeContext context; private final boolean isArray; ValueType( ValueTypeContext context, boolean isArray ) { this.context = context; this.isArray = isArray; } } private static final Map<String, ValueType> NAME_TO_VALUE_TYPE = new HashMap<String, ValueType>(); static { mapNameToValueType( new ValueTypeContext( boolean.class, Boolean.class, boolean[].class, Boolean[].class ) ); mapNameToValueType( new ValueTypeContext( byte.class, Byte.class, byte[].class, Byte[].class ) ); mapNameToValueType( new ValueTypeContext( char.class, Character.class, char[].class, Character[].class ) ); mapNameToValueType( new ValueTypeContext( short.class, Short.class, short[].class, Short[].class ) ); mapNameToValueType( new ValueTypeContext( int.class, Integer.class, int[].class, Integer[].class ) ); mapNameToValueType( new ValueTypeContext( long.class, Long.class, long[].class, Long[].class ) ); mapNameToValueType( new ValueTypeContext( float.class, Float.class, float[].class, Float[].class ) ); mapNameToValueType( new ValueTypeContext( double.class, Double.class, double[].class, Double[].class ) ); mapNameToValueType( new ValueTypeContext( String.class, String.class, String[].class, String[].class ) ); } private static final Map<Class<?>, String> VALUE_TYPE_TO_NAME = new HashMap<Class<?>, String>(); static { for ( Map.Entry<String, ValueType> entry : NAME_TO_VALUE_TYPE.entrySet() ) { ValueTypeContext context = entry.getValue().context; VALUE_TYPE_TO_NAME.put( context.fundamentalClass, context.getName() ); VALUE_TYPE_TO_NAME.put( context.boxClass, context.getName() ); VALUE_TYPE_TO_NAME.put( context.fundamentalArrayClass, context.getArrayName() ); VALUE_TYPE_TO_NAME.put( context.boxArrayClass, context.getArrayName() ); } } private static void mapNameToValueType( ValueTypeContext context ) { NAME_TO_VALUE_TYPE.put( context.getName(), new ValueType( context, false ) ); NAME_TO_VALUE_TYPE.put( context.getArrayName(), new ValueType( context, true ) ); } /** * Constructs a new "set" application. */ public Set() { super(); this.addOptionDefinition( "t", new OptionDefinition( OptionValueType.MUST, "Value type, f.ex: String, String[], int, long[], byte a.s.o. " + "If an array type is supplied the value(s) are given in a " + "JSON-style array format, f.ex:\n" + "[321,45324] for an int[] or\n" + "\"['The first string','The second string here']\" for a " + "String[]" ) ); this.addOptionDefinition( "p", new OptionDefinition( OptionValueType.NONE, "Tells the command to set the supplied values as property." ) ); this.addOptionDefinition( "l", new OptionDefinition( OptionValueType.MUST, "Sets one or more labels on the current node." ) ); } @Override public String getDescription() { return "Sets a property on the current node or relationship or label on the current node.\n" + "Usage:\n" + " set <key> <value>\n" + " set -p <key> <value>\n" + " set -l PERSON"; } protected static String getValueTypeName( Class<?> cls ) { return VALUE_TYPE_TO_NAME.get( cls ); } @Override protected Continuation exec( AppCommandParser parser, Session session, Output out ) throws ShellException { boolean forProperty = parser.options().containsKey( "p" ); boolean forLabel = parser.options().containsKey( "l" ); if ( forProperty || !forLabel ) { // Property if ( parser.arguments().size() < 2 ) { throw new ShellException( "Must supply key and value, " + "like: set title \"This is a my title\"" ); } String key = parser.arguments().get( 0 ); ValueType valueType = getValueType( parser ); Object value = parseValue( parser.arguments().get( 1 ), valueType ); NodeOrRelationship thing = getCurrent( session ); thing.setProperty( key, value ); } else { // Label Node node = getCurrent( session ).asNode(); for ( Label label : parseLabels( parser ) ) { node.addLabel( label ); } } return Continuation.INPUT_COMPLETE; } private static Object parseValue( String stringValue, ValueType valueType ) { Object result = null; if ( valueType.isArray ) { Class<?> componentType = valueType.context.boxClass; Object[] rawArray = parseArray( stringValue ); result = Array.newInstance( componentType, rawArray.length ); for ( int i = 0; i < rawArray.length; i++ ) { Array.set( result, i, parseValue( rawArray[ i ].toString(), componentType ) ); } } else { Class<?> componentType = valueType.context.boxClass; result = parseValue( stringValue, componentType ); } return result; } private static Object parseValue( String value, Class<?> type ) { // TODO Are you tellin' me this can't be done in a better way? Object result = null; if ( type.equals( String.class ) ) { result = value; } else if ( type.equals( Boolean.class ) ) { result = Boolean.parseBoolean( value ); } else if ( type.equals( Byte.class ) ) { result = Byte.parseByte( value ); } else if ( type.equals( Character.class ) ) { result = value.charAt( 0 ); } else if ( type.equals( Short.class ) ) { result = Short.parseShort( value ); } else if ( type.equals( Integer.class ) ) { result = Integer.parseInt( value ); } else if ( type.equals( Long.class ) ) { result = Long.parseLong( value ); } else if ( type.equals( Float.class ) ) { result = Float.parseFloat( value ); } else if ( type.equals( Double.class ) ) { result = Double.parseDouble( value ); } else { throw new IllegalArgumentException( "Invalid type " + type ); } return result; } private static ValueType getValueType( AppCommandParser parser ) throws ShellException { String type = parser.options().containsKey( "t" ) ? parser.options().get( "t" ) : String.class.getSimpleName(); ValueType valueType = NAME_TO_VALUE_TYPE.get( type ); if ( valueType == null ) { throw new ShellException( "Invalid value type '" + type + "'" ); } return valueType; } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_Set.java
1,682
public class ScriptEngineViaReflection { private static final String JAVAX_SCRIPT_SCRIPT_ENGINE_MANAGER = "javax.script.ScriptEngineManager"; private static final String JAVAX_SCRIPT_SCRIPT_CONTEXT = "javax.script.ScriptContext"; private final Object scriptEngineManager; private final int engineScopeValue; private final GraphDatabaseShellServer server; public ScriptEngineViaReflection( GraphDatabaseShellServer server ) { this.server = server; Object scriptEngineManager = null; int engineScopeValue = 0; try { Class<?> scriptEngineManagerClass = Class.forName( JAVAX_SCRIPT_SCRIPT_ENGINE_MANAGER ); scriptEngineManager = scriptEngineManagerClass.newInstance(); engineScopeValue = Class.forName( "javax.script.ScriptContext" ).getField( "ENGINE_SCOPE" ).getInt( null ); } catch ( Exception e ) { scriptEngineManager = null; } this.scriptEngineManager = scriptEngineManager; this.engineScopeValue = engineScopeValue; } public Object getJavascriptEngine() throws Exception { return getEngineByName( "javascript" ); } public Object getEngineByName( String name ) throws Exception { if ( scriptEngineManager == null ) { throw new ShellException( "Scripting not available, make sure javax.script.* is available on " + "the classpath in the JVM the shell server runs in" ); } return scriptEngineManager.getClass().getMethod( "getEngineByName", String.class ).invoke( scriptEngineManager, name ); } public Object interpret( Object scriptEngine, String code ) throws Exception { return scriptEngine.getClass().getMethod( "eval", String.class ).invoke( scriptEngine, code ); } public void addDefaultContext( Object scriptEngine, Session session, Output out ) throws Exception, ShellException { addToContext( scriptEngine, "db", server.getDb(), "out", out, "current", session.getCurrent() == null ? null : getCurrent( server, session ).asPropertyContainer() ); } public Object compile( Object scriptEngine, String code ) throws Exception { return scriptEngine.getClass().getMethod( "compile", String.class ).invoke( scriptEngine, code ); } public static String decorateWithImports( String code, String... imports ) { String importCode = ""; for ( String oneImport : imports ) { importCode += importStatement( oneImport ); } return importCode + code; } public Object newContext() throws Exception { return Class.forName( "javax.script.SimpleScriptContext" ).getConstructor().newInstance(); } public Object executeCompiledScript( Object compiledScript, Object context ) throws Exception { Method method = compiledScript.getClass().getMethod( "eval", Class.forName( JAVAX_SCRIPT_SCRIPT_CONTEXT ) ); method.setAccessible( true ); return method.invoke( compiledScript, context ); } public void addToContext( Object scriptEngine, Object... keyValuePairs ) throws Exception { Object context = scriptEngine.getClass().getMethod( "getContext" ).invoke( scriptEngine ); Method setAttributeMethod = context.getClass().getMethod( "setAttribute", String.class, Object.class, Integer.TYPE ); for ( int i = 0; i < keyValuePairs.length; i++ ) { setAttributeMethod.invoke( context, keyValuePairs[i++], keyValuePairs[i], engineScopeValue ); } } public void setContextAttribute( Object context, String key, Object value ) throws Exception { Method setAttributeMethod = context.getClass().getMethod( "setAttribute", String.class, Object.class, Integer.TYPE ); setAttributeMethod.invoke( context, key, value, engineScopeValue ); } private static String importStatement( String thePackage ) { return "importPackage(Packages." + thePackage + ");"; } }
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_ScriptEngineViaReflection.java
1,683
{ @Override public boolean accept( IndexDefinition item ) { return item.getLabel().name().equals( label.name() ); } }, indexes );
false
community_shell_src_main_java_org_neo4j_shell_kernel_apps_Schema.java
1,684
class FakeShellServer extends GraphDatabaseShellServer { public FakeShellServer( GraphDatabaseAPI graphDb ) throws RemoteException { super( graphDb ); } public int getActiveTransactionCount() { return transactions.size(); } }
false
community_shell_src_test_java_org_neo4j_shell_TestTransactionApps.java
1,685
public class DontShutdownClient { public static void main( String[] args ) throws Exception { GraphDatabaseShellServer server = new GraphDatabaseShellServer( args[0], false, null ); new SameJvmClient( new HashMap<String, Serializable>(), server, /* Temporary, switch back to SilentOutput once flaky test is resolved. */ new SystemOutput() ); server.shutdown(); // Intentionally don't shutdown the client } }
false
community_shell_src_test_java_org_neo4j_shell_DontShutdownClient.java
1,686
public class TestEphemeralFileChannel { @Test public void smoke() throws Exception { EphemeralFileSystemAbstraction fs = new EphemeralFileSystemAbstraction(); StoreChannel channel = fs.open( new File( "yo" ), "rw" ); // Clear it because we depend on it to be zeros where we haven't written ByteBuffer buffer = allocateDirect( 23 ); buffer.put( new byte[23] ); // zeros buffer.flip(); channel.write( buffer ); channel = fs.open( new File("yo"), "rw" ); long longValue = 1234567890L; // [1].....[2]........[1234567890L]... buffer.clear(); buffer.limit( 1 ); buffer.put( (byte) 1 ); buffer.flip(); channel.write( buffer ); buffer.clear(); buffer.limit( 1 ); buffer.put( (byte) 2 ); buffer.flip(); channel.position( 6 ); channel.write( buffer ); buffer.clear(); buffer.limit( 8 ); buffer.putLong( longValue ); buffer.flip(); channel.position( 15 ); channel.write( buffer ); assertEquals( 23, channel.size() ); // Read with position // byte 0 buffer.clear(); buffer.limit( 1 ); channel.read( buffer, 0 ); buffer.flip(); assertEquals( (byte) 1, buffer.get() ); // bytes 5-7 buffer.clear(); buffer.limit( 3 ); channel.read( buffer, 5 ); buffer.flip(); assertEquals( (byte) 0, buffer.get() ); assertEquals( (byte) 2, buffer.get() ); assertEquals( (byte) 0, buffer.get() ); // bytes 15-23 buffer.clear(); buffer.limit( 8 ); channel.read( buffer, 15 ); buffer.flip(); assertEquals( longValue, buffer.getLong() ); fs.shutdown(); } @Test @Ignore public void absoluteVersusRelative() throws Exception { // GIVEN File file = new File( "myfile" ); EphemeralFileSystemAbstraction fs = new EphemeralFileSystemAbstraction(); StoreChannel channel = fs.open( file, "rw" ); byte[] bytes = "test".getBytes(); channel.write( ByteBuffer.wrap( bytes ) ); channel.close(); // WHEN channel = fs.open( new File( file.getAbsolutePath() ), "r" ); byte[] readBytes = new byte[bytes.length]; int nrOfReadBytes = channel.read( ByteBuffer.wrap( readBytes ) ); // THEN assertEquals( bytes.length, nrOfReadBytes ); assertTrue( Arrays.equals( bytes, readBytes ) ); fs.shutdown(); } @Test public void listFiles() throws Exception { /* GIVEN * root * / \ * ----------- dir1 dir2 * / / | \ * subdir1 file file2 file * | * file */ EphemeralFileSystemAbstraction fs = new EphemeralFileSystemAbstraction(); File root = new File( "root" ); File dir1 = new File( root, "dir1" ); File dir2 = new File( root, "dir2" ); File subdir1 = new File( dir1, "sub" ); File file1 = new File( dir1, "file" ); File file2 = new File( dir1, "file2" ); File file3 = new File( dir2, "file" ); File file4 = new File( subdir1, "file" ); fs.mkdirs( dir2 ); fs.mkdirs( dir1 ); fs.mkdirs( subdir1 ); fs.create( file1 ); fs.create( file2 ); fs.create( file3 ); fs.create( file4 ); // THEN assertEquals( asSet( dir1, dir2 ), asSet( fs.listFiles( root ) ) ); assertEquals( asSet( subdir1, file1, file2 ), asSet( fs.listFiles( dir1 ) ) ); assertEquals( asSet( file3 ), asSet( fs.listFiles( dir2 ) ) ); assertEquals( asSet( file4 ), asSet( fs.listFiles( subdir1 ) ) ); fs.shutdown(); } }
false
community_kernel_src_test_java_org_neo4j_metatest_TestEphemeralFileChannel.java
1,687
@Ignore("This feature has to be done some other way") public class ExecutionTimeLimitTest { // ------------------------------ FIELDS ------------------------------ private WrappingNeoServerBootstrapper testBootstrapper; private InternalAbstractGraphDatabase db; private long wait; // -------------------------- OTHER METHODS -------------------------- @Test(expected = UniformInterfaceException.class) public void expectLimitation() { wait = 2000; Client.create().resource( "http://localhost:7476/db/data/node/0" ) .header( "accept", "application/json" ) .get( String.class ); } @Test(expected = UniformInterfaceException.class) public void expectLimitationByHeader() { wait = 200; Client.create().resource( "http://localhost:7476/db/data/node/0" ) .header( "accept", "application/json" ) .header( "max-execution-time", "100" ) .get( String.class ); } @Test public void expectNoLimitation() { wait = 200; Client.create().resource( "http://localhost:7476/db/data/node/0" ) .header( "accept", "application/json" ) .get( String.class ); } @Before @SuppressWarnings("deprecation") public void setUp() throws Exception { db = new ImpermanentGraphDatabase() { @Override public Node getNodeById( long id ) { try { Thread.sleep( wait ); } catch ( InterruptedException e ) { throw new RuntimeException( e ); } return super.getNodeById( id ); } }; ServerConfigurator config = new ServerConfigurator( db ); config.configuration().setProperty( Configurator.WEBSERVER_PORT_PROPERTY_KEY, 7476 ); config.configuration().setProperty( Configurator.WEBSERVER_LIMIT_EXECUTION_TIME_PROPERTY_KEY, 1000 ); testBootstrapper = new WrappingNeoServerBootstrapper( db, config ); testBootstrapper.start(); } @After public void tearDown() { testBootstrapper.stop(); db.shutdown(); } }
false
community_server_src_test_java_org_neo4j_server_web_ExecutionTimeLimitTest.java
1,688
public class StatisticRecord implements Serializable { private final long timeStamp; private final long period; private final long requests; private final StatisticData duration; private final StatisticData size; public StatisticRecord( long timeStamp, long period, long requests, StatisticData duration, StatisticData size ) { this.timeStamp = timeStamp; this.period = period; this.requests = requests; this.duration = duration; this.size = size; } public StatisticData getDuration() { return duration; } public long getPeriod() { return period; } public long getRequests() { return requests; } public StatisticData getSize() { return size; } public long getTimeStamp() { return timeStamp; } @Override public String toString() { return "StatisticRecord{" + "timeStamp=" + timeStamp + ", period=" + period + ", requests=" + requests + ", duration=" + duration + ", size=" + size + '}'; } }
false
community_server_src_main_java_org_neo4j_server_statistic_StatisticRecord.java
1,689
public class StatisticFilter implements Filter { private final StatisticCollector collector; public StatisticFilter( final StatisticCollector collector ) { this.collector = collector; } @Override public void init( FilterConfig filterConfig ) throws ServletException { } @Override public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain ) throws IOException, ServletException { final Long start = nanoTime(); try { chain.doFilter( request, response ); } finally { collector.update( ( nanoTime() - start ) / 1000000.0, getResponseSize( response ) ); } } private long getResponseSize( final ServletResponse response ) { if ( response instanceof ServletResponseWrapper ) { ServletResponseWrapper wrapper = (ServletResponseWrapper) response; return getResponseSize( wrapper.getResponse() ); } if ( response instanceof Response ) { return ( (Response) response ).getContentCount(); } return 0; } @Override public void destroy() { } }
false
community_server_src_main_java_org_neo4j_server_statistic_StatisticFilter.java
1,690
public class StatisticData implements Serializable { private static final long serialVersionUID = 1006656694124740870L; private static final int MEDIAN_MAX = 3000; private int[] requests = new int[MEDIAN_MAX]; private int count = 0; private double sum = 0; private double sumSq = 0; private double min = 0; private double max = 0; public StatisticData() { } private StatisticData( int count, double sum, double sumSq, double min, double max, int[] requests ) { this.count = count; this.sum = sum; this.sumSq = sumSq; this.min = min; this.max = max; System.arraycopy( requests, 0, this.requests, 0, MEDIAN_MAX ); } public double getAvg() { double avg = 0; if ( count > 1 ) { avg = sum / count; } return avg; } private double getVar() { double var = 0; if ( count > 2 ) { var = Math.sqrt( ( sumSq - sum * sum / count ) / ( count - 1 ) ); } return var; } public int getMedian() { int c = 0; int medianPoint = count / 2; for ( int i = 0; i < MEDIAN_MAX; i++ ) { c += requests[i]; if ( c >= medianPoint ) { return i; } } return MEDIAN_MAX; } @Override public String toString() { return "StatisticData{" + "count=" + count + ", sum=" + sum + ", min=" + min + ", max=" + max + ", avg=" + getAvg() + ", var=" + getVar() + ", median=" + getMedian() + '}'; } public StatisticData copy() { return new StatisticData( count, sum, sumSq, min, max, requests ); } public void addValue( double value ) { min = count > 0 && min < value ? min : value; max = count > 0 && max > value ? max : value; count += 1; sum += value; sumSq += value * value; int v = value >= MEDIAN_MAX ? MEDIAN_MAX - 1 : value < 0 ? 0 : (int) value; requests[v]++; } public double getMin() { return min; } public double getMax() { return max; } public double getSum() { return sum; } }
false
community_server_src_main_java_org_neo4j_server_statistic_StatisticData.java
1,691
public class StatisticCollector { private volatile long start = System.currentTimeMillis(); private volatile StatisticData currentSize = new StatisticData(); private volatile StatisticData currentDuration = new StatisticData(); private final AtomicLong count = new AtomicLong( 0l ); private StatisticRecord snapshot = createSnapshot(); public StatisticRecord currentSnapshot() { return snapshot; } public synchronized StatisticRecord createSnapshot() { final StatisticData previousDuration, previousSize; final long timeStamp, period, previousCount, previousStart; synchronized (this) { previousDuration = currentDuration.copy(); previousSize = currentSize.copy(); previousCount = count.get(); previousStart = start; currentDuration = new StatisticData(); currentSize = new StatisticData(); start = System.currentTimeMillis(); count.set( 0l ); timeStamp = start; period = ( start - previousStart ); } return snapshot = new StatisticRecord( timeStamp, period, previousCount, previousDuration, previousSize ); } /** * add one datapoint for statistics * * @param time duration of the request * @param size size in bytes of the request */ public synchronized void update( final double time, final long size ) { currentDuration.addValue( time ); currentSize.addValue( size ); count.incrementAndGet(); } }
false
community_server_src_main_java_org_neo4j_server_statistic_StatisticCollector.java
1,692
public class TestSslCertificateFactory { private File cPath; private File pkPath; @Test public void shouldCreateASelfSignedCertificate() throws Exception { SslCertificateFactory sslFactory = new SslCertificateFactory(); sslFactory.createSelfSignedCertificate( cPath, pkPath, "myhost" ); // Attempt to load certificate Certificate[] certificates = sslFactory.loadCertificates( cPath ); assertThat( certificates.length, is( greaterThan( 0 ) ) ); // Attempt to load private key PrivateKey pk = sslFactory.loadPrivateKey( pkPath ); assertThat( pk, notNullValue() ); } @Before public void createFiles() throws Exception { cPath = File.createTempFile( "cert", "test" ); pkPath = File.createTempFile( "privatekey", "test" ); } @After public void deleteFiles() throws Exception { pkPath.delete(); cPath.delete(); } }
false
community_server_src_test_java_org_neo4j_server_security_TestSslCertificateFactory.java
1,693
public class SslSocketConnectorFactory extends HttpConnectorFactory { public ServerConnector createConnector( Server server, KeyStoreInformation config, String host, int port, int jettyMaxThreads ) { SslConnectionFactory sslConnectionFactory = createSslConnectionFactory( config ); return super.createConnector( server, host, port, jettyMaxThreads, sslConnectionFactory, createHttpConnectionFactory() ); } private SslConnectionFactory createSslConnectionFactory( KeyStoreInformation config ) { SslContextFactory sslContextFactory = new SslContextFactory(); sslContextFactory.setKeyStorePath( config.getKeyStorePath() ); sslContextFactory.setKeyStorePassword( String.valueOf( config.getKeyStorePassword() ) ); sslContextFactory.setKeyManagerPassword( String.valueOf( config.getKeyPassword() ) ); return new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()); } }
false
community_server_src_main_java_org_neo4j_server_security_SslSocketConnectorFactory.java
1,694
public class SslCertificateFactory { private static final String CERTIFICATE_TYPE = "X.509"; private static final String KEY_ENCRYPTION = "RSA"; { Security.addProvider(new BouncyCastleProvider()); } public void createSelfSignedCertificate(File certificatePath, File privateKeyPath, String hostName) { FileOutputStream fos = null; try { KeyPairGenerator keyPairGenerator = KeyPairGenerator .getInstance(KEY_ENCRYPTION); keyPairGenerator.initialize(1024); KeyPair keyPair = keyPairGenerator.generateKeyPair(); X509V3CertificateGenerator certGenertor = new X509V3CertificateGenerator(); certGenertor.setSerialNumber(BigInteger.valueOf( new SecureRandom().nextInt()).abs()); certGenertor.setIssuerDN(new X509Principal("CN=" + hostName + ", OU=None, O=None L=None, C=None")); certGenertor.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30)); certGenertor.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10))); certGenertor.setSubjectDN(new X509Principal("CN=" + hostName + ", OU=None, O=None L=None, C=None")); certGenertor.setPublicKey(keyPair.getPublic()); certGenertor.setSignatureAlgorithm("MD5WithRSAEncryption"); Certificate certificate = certGenertor.generate( keyPair.getPrivate(), "BC"); ensureFolderExists(certificatePath.getParentFile()); ensureFolderExists(privateKeyPath.getParentFile()); fos = new FileOutputStream(certificatePath); fos.write(certificate.getEncoded()); fos.close(); fos = new FileOutputStream(privateKeyPath); fos.write(keyPair.getPrivate().getEncoded()); fos.close(); } catch (Exception e) { throw new RuntimeException("Unable to create self signed SSL certificate, please see nested exception.", e); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { throw new RuntimeException(e); } } } } public Certificate[] loadCertificates(File certFile) throws CertificateException, FileNotFoundException { FileInputStream fis = null; try { fis = new FileInputStream(certFile); Collection<? extends Certificate> certificates = CertificateFactory.getInstance(CERTIFICATE_TYPE).generateCertificates( fis); return certificates.toArray(new Certificate[]{}); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { throw new RuntimeException(e); } } } } public PrivateKey loadPrivateKey(File privateKeyFile) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { DataInputStream dis = null; try { FileInputStream fis = new FileInputStream(privateKeyFile); dis = new DataInputStream(fis); byte[] keyBytes = new byte[(int) privateKeyFile.length()]; dis.readFully(keyBytes); KeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes); return KeyFactory.getInstance(KEY_ENCRYPTION).generatePrivate(keySpec); } catch (FileNotFoundException e ) { throw new IOException("Could not find private key file to use for SSL support, see nested exception.", e); } finally { if (dis != null) { try { dis.close(); } catch (IOException e) { throw new RuntimeException(e); } } } } private void ensureFolderExists(File path) { if(!path.exists()) { path.mkdirs(); } } }
false
community_server_src_main_java_org_neo4j_server_security_SslCertificateFactory.java
1,695
public class KeyStoreInformation { private final String keyStorePath; private final char[] keyStorePassword; private final char[] keyPassword; public KeyStoreInformation(String keyStorePath, char[] keyStorePassword, char[] keyPassword) { this.keyStorePassword = keyStorePassword; this.keyStorePath = keyStorePath; this.keyPassword = keyPassword; } public String getKeyStorePath() { return keyStorePath; } public char[] getKeyStorePassword() { return keyStorePassword; } public char[] getKeyPassword() { return keyPassword; } }
false
community_server_src_main_java_org_neo4j_server_security_KeyStoreInformation.java
1,696
public class KeyStoreFactoryTest { @Test public void shouldCreateKeyStoreForGivenKeyPair() throws Exception { // given File certificatePath = File.createTempFile( "cert", "test" ); File privateKeyPath = File.createTempFile( "privatekey", "test" ); File keyStorePath = File.createTempFile( "keyStore", "test" ); new SslCertificateFactory().createSelfSignedCertificate( certificatePath, privateKeyPath, "some-hostname" ); // when KeyStoreInformation ks = new KeyStoreFactory().createKeyStore( keyStorePath, privateKeyPath, certificatePath ); // then assertThat( new File( ks.getKeyStorePath() ).exists(), is( true ) ); } @Test public void shouldImportSingleCertificateWhenNotInAChain() throws Exception { // given File certificatePath = File.createTempFile( "cert", "test" ); File privateKeyPath = File.createTempFile( "privatekey", "test" ); File keyStorePath = File.createTempFile( "keyStore", "test" ); new SslCertificateFactory().createSelfSignedCertificate( certificatePath, privateKeyPath, "some-hostname" ); KeyStoreInformation keyStoreInformation = new KeyStoreFactory().createKeyStore( keyStorePath, privateKeyPath, certificatePath ); KeyStore keyStore = KeyStore.getInstance( "JKS" ); keyStore.load( new FileInputStream( keyStoreInformation.getKeyStorePath() ), keyStoreInformation.getKeyStorePassword() ); // when Certificate[] chain = keyStore.getCertificateChain( "key" ); // then assertEquals( "Single certificate expected not a chain of [" + chain.length + "]", 1, chain.length ); } @Test public void shouldImportAllCertificatesInAChain() throws Exception { // given File keyStorePath = File.createTempFile( "keyStore", "test" ); File privateKeyPath = fileFromResources( "/certificates/chained_key.der" ); File certificatePath = fileFromResources( "/certificates/combined.pem" ); KeyStoreInformation keyStoreInformation = new KeyStoreFactory().createKeyStore( keyStorePath, privateKeyPath, certificatePath ); KeyStore keyStore = KeyStore.getInstance( "JKS" ); keyStore.load( new FileInputStream( keyStoreInformation.getKeyStorePath() ), keyStoreInformation.getKeyStorePassword() ); // when Certificate[] chain = keyStore.getCertificateChain( "key" ); // then assertEquals( "3 certificates expected in chain: root, intermediary, and user's", 3, chain.length ); } private File fileFromResources( String path ) { URL url = this.getClass().getResource( path ); return new File( url.getFile() ); } }
false
community_server_src_test_java_org_neo4j_server_security_KeyStoreFactoryTest.java
1,697
public class KeyStoreFactory { private SslCertificateFactory sslCertificateFactory; public KeyStoreFactory() { this.sslCertificateFactory = new SslCertificateFactory(); } public KeyStoreInformation createKeyStore( File keyStorePath, File privateKeyPath, File certificatePath ) { try { char[] keyStorePassword = getRandomChars( 50 ); char[] keyPassword = getRandomChars( 50 ); createKeyStore( keyStorePath, keyStorePassword, keyPassword, privateKeyPath, certificatePath ); return new KeyStoreInformation( keyStorePath.getAbsolutePath(), keyStorePassword, keyPassword ); } catch ( Exception e ) { throw new RuntimeException( "Unable to setup keystore for SSL certificate, see nested exception.", e ); } } private void createKeyStore( File keyStorePath, char[] keyStorePassword, char[] keyPassword, File privateKeyFile, File certFile ) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, InvalidKeyException, InvalidKeySpecException, NoSuchPaddingException, InvalidAlgorithmParameterException { FileOutputStream fis = null; try { if ( keyStorePath.exists() ) { keyStorePath.delete(); } ensureFolderExists( keyStorePath.getParentFile() ); KeyStore keyStore = KeyStore.getInstance( "JKS" ); keyStore.load( null, keyStorePassword ); keyStore.setKeyEntry( "key", sslCertificateFactory.loadPrivateKey( privateKeyFile ), keyPassword, sslCertificateFactory.loadCertificates( certFile ) ); fis = new FileOutputStream( keyStorePath.getAbsolutePath() ); keyStore.store( fis, keyStorePassword ); } finally { if ( fis != null ) { try { fis.close(); } catch ( IOException e ) { throw new RuntimeException( e ); } } } } private char[] getRandomChars( int length ) { SecureRandom rand = new SecureRandom(); char[] chars = new char[length]; for ( int i = 0; i < length; i++ ) { chars[i] = (char) rand.nextInt(); } return chars; } private void ensureFolderExists( File path ) { if ( !path.exists() ) { path.mkdirs(); } } }
false
community_server_src_main_java_org_neo4j_server_security_KeyStoreFactory.java
1,698
public static class JavascriptJavaObject extends NativeJavaObject { public JavascriptJavaObject( Scriptable scope, Object javaObject, Class type ) { // we pass 'null' to object. NativeJavaObject uses // passed 'type' to reflect fields and methods when // object is null. super(scope, null, type); // Now, we set actual object. 'javaObject' is protected // field of NativeJavaObject. this.javaObject = javaObject; } }
false
community_server_src_main_java_org_neo4j_server_scripting_javascript_WhiteListJavaWrapper.java
1,699
public class WhiteListJavaWrapper extends WrapFactory { private final ClassShutter classShutter; public WhiteListJavaWrapper( ClassShutter classShutter ) { this.classShutter = classShutter; } public static class JavascriptJavaObject extends NativeJavaObject { public JavascriptJavaObject( Scriptable scope, Object javaObject, Class type ) { // we pass 'null' to object. NativeJavaObject uses // passed 'type' to reflect fields and methods when // object is null. super(scope, null, type); // Now, we set actual object. 'javaObject' is protected // field of NativeJavaObject. this.javaObject = javaObject; } } /* * Majority of code below from Rhino source, written by A. Sundararajan. */ @Override public Scriptable wrapAsJavaObject(Context cx, Scriptable scope, Object javaObject, Class staticType) { if (javaObject instanceof ClassLoader) { throw new SecurityException( "Class loaders cannot be accessed in this environment." ); } else { String name = null; if (javaObject instanceof Class) { name = ((Class)javaObject).getName(); } else if (javaObject instanceof Member ) { Member member = (Member) javaObject; // Check member access. Don't allow reflective access to // non-public members. Note that we can't call checkMemberAccess // because that expects exact stack depth! if (!Modifier.isPublic( member.getModifiers() )) { return null; } name = member.getDeclaringClass().getName(); } // Now, make sure that no ClassShutter prevented Class or Member // of it is accessed reflectively. Note that ClassShutter may // prevent access to a class, even though SecurityManager permit. if (name != null) { if (!classShutter.visibleToScripts(name)) { throw new SecurityException( "'"+name+"' cannot be accessed in this environment." ); } else { return new NativeJavaObject(scope, javaObject, staticType); } } } // we have got some non-reflective object. Class dynamicType = javaObject.getClass(); String name = dynamicType.getName(); if (!classShutter.visibleToScripts(name)) { // Object of some sensitive class (such as sun.net.www.* // objects returned from public method of java.net.URL class. // We expose this object as though it is an object of some // super class that is safe for access. Class type = null; // Whenever a Java Object is wrapped, we are passed with a // staticType which is the type found from environment. For // example, method return type known from signature. The dynamic // type would be the actual Class of the actual returned object. // If the staticType is an interface, we just use that type. if (staticType != null && staticType.isInterface()) { type = staticType; } else { // dynamicType is always a class type and never an interface. // find an accessible super class of the dynamic type. while (true) { dynamicType = dynamicType.getSuperclass(); if(dynamicType != null) { name = dynamicType.getName(); if (classShutter.visibleToScripts(name)) { type = dynamicType; break; } } else { break; } } // atleast java.lang.Object has to be accessible. So, when // we reach here, type variable should not be null. assert type != null: "even java.lang.Object is not accessible?"; } // create custom wrapper with the 'safe' type. return new JavascriptJavaObject(scope, javaObject, type); } else { return new NativeJavaObject(scope, javaObject, staticType); } } }
false
community_server_src_main_java_org_neo4j_server_scripting_javascript_WhiteListJavaWrapper.java