Unnamed: 0
int64 0
6.7k
| func
stringlengths 12
89.6k
| target
bool 2
classes | project
stringlengths 45
151
|
|---|---|---|---|
1,700
|
public class WhiteListClassShutter implements ClassShutter
{
private Set<String> whiteList;
public WhiteListClassShutter(Set<String> whiteList)
{
this.whiteList = whiteList;
}
@Override
public boolean visibleToScripts( String className )
{
return whiteList.contains( className );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_scripting_javascript_WhiteListClassShutter.java
|
1,701
|
public class TestWhiteListJavaWrapper
{
@After
public void exitContext()
{
try {
Context.exit();
} catch (IllegalStateException e)
{
// Om nom nom
}
}
@Test(expected = SecurityException.class)
public void shouldBlockAttemptsAtAccessingClassLoader() throws Exception
{
// Given
WhiteListJavaWrapper wrapper = new WhiteListJavaWrapper( new WhiteListClassShutter( new HashSet<String>( ) ));
// When
wrapper.wrap( null, null, getClass().getClassLoader(), null );
}
@Test
public void shouldDownCastSubclassesToAllowedParentClass() throws Exception
{
// Given
Set<String> whiteList = new HashSet<String>( );
whiteList.add( Object.class.getName() );
WhiteListJavaWrapper wrapper = new WhiteListJavaWrapper( new WhiteListClassShutter( whiteList ));
Context cx = Context.enter();
Scriptable scope = cx.initStandardObjects();
// When
Object wrapped = wrapper.wrap( cx, scope, new TestWhiteListJavaWrapper(), null );
// Then
assertThat( wrapped, is( instanceOf( NativeJavaObject.class ) ) );
NativeJavaObject obj = (NativeJavaObject)wrapped;
assertThat( obj.has( "aGetter", scope ), is( false ));
assertThat( (UniqueTag) obj.get( "aGetter", scope ), is( UniqueTag.NOT_FOUND ) );
}
@Test(expected = SecurityException.class)
public void shouldThrowSecurityExceptionWhenAccessingLockedClasses() throws Exception
{
// Given
Set<String> whiteList = new HashSet<String>( );
whiteList.add( Object.class.getName() );
WhiteListJavaWrapper wrapper = new WhiteListJavaWrapper( new WhiteListClassShutter( whiteList ));
Context cx = Context.enter();
Scriptable scope = cx.initStandardObjects();
// When
Object wrapped = wrapper.wrap( cx, scope, TestWhiteListJavaWrapper.class, null );
}
@Test
public void shouldAllowAccessToWhiteListedClassMembers() throws Exception
{
// XXX: The Rhino security stuff can only be set globally, unfortunately. That means
// that we need to use a class here that is white-listed in the "real" white list, because
// other tests will already have configured global security settings that we cannot override.
// Given
WhiteListJavaWrapper wrapper = new WhiteListJavaWrapper( new WhiteListClassShutter(
UserScriptClassWhiteList.getWhiteList() ));
Context cx = Context.enter();
Scriptable scope = cx.initStandardObjects();
// When
Object wrapped = wrapper.wrap( cx, scope, DynamicRelationshipType.withName( "blah" ), null );
// Then
assertThat( wrapped, is( instanceOf( NativeJavaObject.class ) ) );
NativeJavaObject obj = (NativeJavaObject)wrapped;
assertThat( obj.get( "name", scope ),
is( instanceOf( NativeJavaMethod.class ) ) );
}
public void aGetter()
{
}
}
| false
|
community_server_src_test_java_org_neo4j_server_scripting_javascript_TestWhiteListJavaWrapper.java
|
1,702
|
public class TestWhiteListClassShutter
{
@Test
public void shouldAllowWhiteListedClasses() throws Exception
{
// Given
Set<String> whiteList = new HashSet<String>();
whiteList.add( getClass().getName() );
WhiteListClassShutter shutter = new WhiteListClassShutter(whiteList);
// When
boolean visible = shutter.visibleToScripts( getClass().getName() );
// Then
assertThat(visible, is(true));
}
@Test
public void shouldDisallowUnlistedClasses() throws Exception
{
WhiteListClassShutter shutter = new WhiteListClassShutter(new HashSet<String>());
// When
boolean visible = shutter.visibleToScripts( getClass().getName() );
// Then
assertThat(visible, is(false));
}
}
| false
|
community_server_src_test_java_org_neo4j_server_scripting_javascript_TestWhiteListClassShutter.java
|
1,703
|
public class TestJavascriptSecurityRestrictions
{
public static void methodThatShouldNotBeCallable()
{
}
@BeforeClass
public static void doBullshitGlobalStateCrap()
{
GlobalJavascriptInitializer.initialize( GlobalJavascriptInitializer.Mode.SANDBOXED );
}
@Test
public void shouldBeAbleToAccessWhiteListedThings() throws Exception
{
// Given
String classThatShouldBeInaccessible = TestJavascriptSecurityRestrictions.class.getName();
ScriptExecutor executor = new JavascriptExecutor(
Evaluation.class.getName() + ".INCLUDE_AND_CONTINUE;" );
// When
Object result = executor.execute( null );
// Then
assertThat( result, is( instanceOf( Evaluation.class ) ) );
assertThat( (Evaluation) result, is(Evaluation.INCLUDE_AND_CONTINUE) );
}
@Test(expected = EvaluationException.class)
public void shouldNotBeAbleToImportUnsafeClasses() throws Exception
{
// Given
String classThatShouldBeInaccessible = TestJavascriptSecurityRestrictions.class.getName();
ScriptExecutor executor = new JavascriptExecutor(
classThatShouldBeInaccessible + ".methodThatShouldNotBeCallable();" );
// When
executor.execute( null );
}
@Test(expected = EvaluationException.class)
public void shouldNotBeAbleToUseReflectionToInstantiateThings() throws Exception
{
// Given
ScriptExecutor executor = new JavascriptExecutor(
Evaluation.class.getName() + ".getClass().getClassLoader();" );
// When
executor.execute( null );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_scripting_javascript_TestJavascriptSecurityRestrictions.java
|
1,704
|
public class TestJavascriptExecutor
{
@Test
public void shouldExecuteBasicScript() throws Exception
{
// Given
JavascriptExecutor executor = new JavascriptExecutor( "1337;" );
// When
Object out = executor.execute( null );
// Then
assertThat( out, not(nullValue()));
assertThat( (Integer) out, is( 1337 ) );
}
@Test
public void shouldAllowContextVariables() throws Exception
{
// Given
JavascriptExecutor executor = new JavascriptExecutor( "myVar;" );
Map<String, Object> ctx = new HashMap<String, Object>();
ctx.put( "myVar", 1338 );
// When
Object out = executor.execute( ctx );
// Then
assertThat( out, not( nullValue() ));
assertThat( (Integer) out, is( 1338 ));
}
@Test
public void shouldBeAbleToReuseExecutor() throws Exception
{
// Given
JavascriptExecutor executor = new JavascriptExecutor( "1337;" );
// When
Object out1 = executor.execute( null );
Object out2 = executor.execute( null );
// Then
assertThat( (Integer) out1, is( 1337 ) );
assertThat( (Integer) out2, is( 1337 ) );
}
@Test
public void varsSetInOneExecutionShouldNotBeAvailableInAnother() throws Exception
{
// Given
JavascriptExecutor executor = new JavascriptExecutor(
"if(firstRun) { " +
" this['theVar'] = 'boo'; " +
"} else { " +
" this['theVar']; " +
"}" );
Map<String, Object> ctx = new HashMap<String, Object>();
// When
ctx.put( "firstRun", true );
Object out1 = executor.execute( ctx );
ctx.put( "firstRun", false );
Object out2 = executor.execute( ctx );
// Then
assertThat( (String) out1, is( "boo" ) );
assertThat( out2, is( nullValue()) );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_scripting_javascript_TestJavascriptExecutor.java
|
1,705
|
public class TestGlobalJavascriptInitializer
{
@Test(expected = RuntimeException.class )
public void shouldNotAllowChangingMode() throws Exception
{
// Given
GlobalJavascriptInitializer.initialize( GlobalJavascriptInitializer.Mode.SANDBOXED );
// When
GlobalJavascriptInitializer.initialize( GlobalJavascriptInitializer.Mode.UNSAFE );
}
@Test
public void initializingTheSameModeTwiceIsFine() throws Exception
{
// Given
GlobalJavascriptInitializer.initialize( GlobalJavascriptInitializer.Mode.SANDBOXED );
// When
GlobalJavascriptInitializer.initialize( GlobalJavascriptInitializer.Mode.SANDBOXED );
// Then
// no exception should have been thrown.
}
}
| false
|
community_server_src_test_java_org_neo4j_server_scripting_javascript_TestGlobalJavascriptInitializer.java
|
1,706
|
public static class Factory implements ScriptExecutor.Factory
{
/**
* Note that you can set sandbox/no sandbox once, after that it is globally defined
* for the JVM. If you create a new factory with a different sandboxing setting, an
* exception will be thrown.
*
* @param enableSandboxing
*/
public Factory(boolean enableSandboxing)
{
if(enableSandboxing)
{
GlobalJavascriptInitializer.initialize( GlobalJavascriptInitializer.Mode.SANDBOXED );
} else
{
GlobalJavascriptInitializer.initialize( GlobalJavascriptInitializer.Mode.UNSAFE );
}
}
@Override
public ScriptExecutor createExecutorForScript( String script ) throws EvaluationException
{
return new JavascriptExecutor( script );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_scripting_javascript_JavascriptExecutor.java
|
1,707
|
public class StatisticStartupListener implements LifeCycle.Listener
{
private final Server jetty;
private final FilterHolder holder;
private final ConsoleLogger log;
public StatisticStartupListener( Server jetty, StatisticFilter statisticFilter, Logging logging )
{
this.jetty = jetty;
holder = new FilterHolder( statisticFilter );
this.log = logging.getConsoleLog( getClass() );
}
@Override
public void lifeCycleStarting( final LifeCycle event )
{
}
@Override
public void lifeCycleStarted( final LifeCycle event )
{
for ( Handler handler : jetty.getHandlers() )
{
if ( handler instanceof ServletContextHandler )
{
final ServletContextHandler context = (ServletContextHandler) handler;
final String path = context.getContextPath();
log.log( "adding statistic-filter to " + path );
context.addFilter( holder, "/*", EnumSet.allOf(DispatcherType.class) );
}
}
}
@Override
public void lifeCycleFailure( final LifeCycle event, final Throwable cause )
{
}
@Override
public void lifeCycleStopping( final LifeCycle event )
{
log.log( "stopping filter" );
try {
holder.doStop();
} catch (Exception e) {
throw new RuntimeException(e); // TODO what's appropriate here?
}
}
@Override
public void lifeCycleStopped( final LifeCycle event )
{
}
public void stop()
{
log.log( "stopping listeneer" );
jetty.removeLifeCycleListener( this );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_statistic_StatisticStartupListener.java
|
1,708
|
{
@Override
public Node getNodeById( long id )
{
try
{
Thread.sleep( wait );
} catch ( InterruptedException e )
{
throw new RuntimeException( e );
}
return super.getNodeById( id );
}
};
| false
|
community_server_src_test_java_org_neo4j_server_web_ExecutionTimeLimitTest.java
|
1,709
|
{
protected Context makeContext()
{
Context cx = super.makeContext();
ClassShutter shutter = new WhiteListClassShutter( UserScriptClassWhiteList.getWhiteList() );
cx.setLanguageVersion( Context.VERSION_1_7 );
// TODO: This goes up to 9, do performance tests to determine appropriate level of optimization
cx.setOptimizationLevel( 4 );
cx.setClassShutter( shutter );
cx.setWrapFactory( new WhiteListJavaWrapper( shutter ) );
return cx;
}
};
| false
|
community_server_src_main_java_org_neo4j_server_scripting_javascript_GlobalJavascriptInitializer.java
|
1,710
|
@Path( HelloWorldWebResource.ROOT_PATH )
public class HelloWorldWebResource
{
public static final String ROOT_PATH = "/greeting";
@Consumes( "text/plain" )
@Produces( "text/plain" )
@POST
public Response sayHello( String name )
{
return Response.ok()
.entity( "hello, " + name )
.type( "text/plain" )
.build();
}
}
| false
|
community_server_src_test_java_org_neo4j_server_web_HelloWorldWebResource.java
|
1,711
|
@Provider
public class WebServerProvider extends InjectableProvider<WebServer>
{
private final WebServer server;
public WebServerProvider( WebServer server )
{
super( WebServer.class );
this.server = server;
}
@Override
public WebServer getValue( HttpContext c )
{
return server;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_web_WebServerProvider.java
|
1,712
|
{
};
| false
|
community_server_src_test_java_org_neo4j_server_web_TestJetty9WebServer.java
|
1,713
|
{
@Override
public <T> T resolveDependency( Class<T> type, SelectionStrategy selector )
throws IllegalArgumentException
{
if ( Logging.class.isAssignableFrom( type ) )
{
return type.cast( DevNullLoggingService.DEV_NULL );
}
return null;
}
};
| false
|
community_server_src_test_java_org_neo4j_server_web_TestJetty9WebServer.java
|
1,714
|
@Path("/")
public class TestJetty9WebServer {
@GET
public Response index()
{
return Response.status( Status.NO_CONTENT )
.build();
}
@Test
public void shouldBeAbleToRestart() throws Throwable
{
// TODO: This is needed because WebServer has a cyclic
// dependency to NeoServer, which should be removed.
// Once that is done, we should instantiate WebServer
// here directly.
AbstractGraphDatabase db = mock(AbstractGraphDatabase.class);
when( db.getDependencyResolver() ).thenReturn( noLoggingDependencyResolver() );
WrappingNeoServer neoServer = new WrappingNeoServer(db);
WebServer server = neoServer.getWebServer();
try
{
server.setAddress("127.0.0.1");
server.setPort(7878);
server.start();
server.stop();
server.start();
}
finally
{
try
{
server.stop();
}
catch( Throwable t )
{
}
}
}
private DependencyResolver noLoggingDependencyResolver()
{
return new DependencyResolver.Adapter()
{
@Override
public <T> T resolveDependency( Class<T> type, SelectionStrategy selector )
throws IllegalArgumentException
{
if ( Logging.class.isAssignableFrom( type ) )
{
return type.cast( DevNullLoggingService.DEV_NULL );
}
return null;
}
};
}
@Test
public void shouldBeAbleToSetExecutionLimit() throws Throwable
{
@SuppressWarnings("deprecation")
ImpermanentGraphDatabase db = new ImpermanentGraphDatabase( "path", stringMap(),
new DefaultGraphDatabaseDependencies())
{
};
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 );
WrappingNeoServerBootstrapper testBootstrapper = new WrappingNeoServerBootstrapper( db, config );
// When
testBootstrapper.start();
testBootstrapper.stop();
// Then it should not have crashed
// TODO: This is a really poor test, but does not feel worth re-visiting right now since we're removing the
// guard in subsequent releases.
}
@Test
public void shouldStopCleanlyEvenWhenItHasntBeenStarted()
{
new Jetty9WebServer( DevNullLoggingService.DEV_NULL ).stop();
}
@Rule
public Mute mute = muteAll();
}
| false
|
community_server_src_test_java_org_neo4j_server_web_TestJetty9WebServer.java
|
1,715
|
public class SimpleUriBuilder {
public URI buildURI(String address, int port, boolean isSsl)
{
StringBuilder sb = new StringBuilder();
sb.append( "http" );
if ( isSsl )
{
sb.append( "s" );
}
sb.append( "://" );
sb.append( address );
if ( port != 80 && port != 443)
{
sb.append( ":" );
sb.append( port );
}
sb.append( "/" );
try
{
return new URI( sb.toString() );
}
catch ( URISyntaxException e )
{
throw new RuntimeException( e );
}
}
}
| false
|
community_server_src_main_java_org_neo4j_server_web_SimpleUriBuilder.java
|
1,716
|
@SuppressWarnings( "serial" )
public class NeoServletContainer extends ServletContainer
{
private final Collection<InjectableProvider<?>> injectables;
public NeoServletContainer( Collection<InjectableProvider<?>> injectables )
{
this.injectables = injectables;
}
@Override
protected void configure( WebConfig wc, ResourceConfig rc, WebApplication wa )
{
super.configure( wc, rc, wa );
Set<Object> singletons = rc.getSingletons();
for ( InjectableProvider<?> injectable : injectables )
{
singletons.add( injectable );
}
}
@Override
protected ResourceConfig getDefaultResourceConfig( Map<String, Object> props, WebConfig wc )
throws ServletException
{
Object classNames = props.get( ClassNamesResourceConfig.PROPERTY_CLASSNAMES );
if ( classNames != null )
{
return new ClassNamesResourceConfig( props );
}
return super.getDefaultResourceConfig( props, wc );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_web_NeoServletContainer.java
|
1,717
|
public class NeoJettyErrorHandler extends ErrorHandler
{
@Override
protected void handleErrorPage(HttpServletRequest request, Writer writer, int code,
String message) throws IOException
{
writeErrorPage(request, writer, code, message, false);
}
@Override
protected void writeErrorPage(HttpServletRequest request, Writer writer, int code, String message,
boolean showStacks) throws IOException {
// we don't want any Jetty output
}
@Override
protected void writeErrorPageHead(HttpServletRequest request, Writer writer, int code,
String message) throws IOException {
// we don't want any Jetty output
}
@Override
protected void writeErrorPageBody(HttpServletRequest request, Writer writer, int code,
String message, boolean showStacks) throws IOException {
// we don't want any Jetty output
}
@Override
protected void writeErrorPageMessage(HttpServletRequest request, Writer writer, int code,
String message, String uri) throws IOException {
// we don't want any Jetty output
}
@Override
protected void writeErrorPageStacks(HttpServletRequest request, Writer writer)
throws IOException {
// we don't want any stack output
}
}
| false
|
community_server_src_main_java_org_neo4j_server_web_NeoJettyErrorHandler.java
|
1,718
|
{
@Override
public void run()
{
try
{
cb.await();
}
catch ( InterruptedException e )
{
e.printStackTrace();
}
catch ( BrokenBarrierException e )
{
e.printStackTrace();
}
}
} );
| false
|
community_server_src_test_java_org_neo4j_server_web_JettyThreadLimitTest.java
|
1,719
|
public class JettyThreadLimitTest
{
@Rule
public Mute mute = muteAll();
@Test
public void shouldHaveConfigurableJettyThreadPoolSize() throws Exception
{
Jetty9WebServer server = new Jetty9WebServer( DevNullLoggingService.DEV_NULL );
final int maxThreads = 7;
server.setMaxThreads( maxThreads );
server.setPort( 7480 );
try {
server.start();
QueuedThreadPool threadPool = (QueuedThreadPool) server.getJetty()
.getThreadPool();
threadPool.start();
int configuredMaxThreads = maxThreads * Runtime.getRuntime().availableProcessors();
loadThreadPool( threadPool, configuredMaxThreads + 1);
int threads = threadPool.getThreads();
assertTrue( threads <= maxThreads );
}
finally
{
server.stop();
}
}
private void loadThreadPool(QueuedThreadPool threadPool, int tasksToSubmit)
{
final CyclicBarrier cb = new CyclicBarrier(tasksToSubmit);
for ( int i = 0; i < tasksToSubmit; i++ )
{
threadPool.dispatch( new Runnable()
{
@Override
public void run()
{
try
{
cb.await();
}
catch ( InterruptedException e )
{
e.printStackTrace();
}
catch ( BrokenBarrierException e )
{
e.printStackTrace();
}
}
} );
}
}
}
| false
|
community_server_src_test_java_org_neo4j_server_web_JettyThreadLimitTest.java
|
1,720
|
public class JettyLifeCycleListenerAdapter implements LifeCycle.Listener
{
@Override
public void lifeCycleStopping( LifeCycle arg0 )
{
}
@Override
public void lifeCycleStopped( LifeCycle arg0 )
{
}
@Override
public void lifeCycleStarting( LifeCycle arg0 )
{
}
@Override
public void lifeCycleStarted( LifeCycle arg0 )
{
}
@Override
public void lifeCycleFailure( LifeCycle arg0, Throwable arg1 )
{
}
}
| false
|
community_server_src_main_java_org_neo4j_server_web_JettyLifeCycleListenerAdapter.java
|
1,721
|
private static class FilterDefinition
{
private final Filter filter;
private final String pathSpec;
public FilterDefinition(Filter filter, String pathSpec)
{
this.filter = filter;
this.pathSpec = pathSpec;
}
public boolean matches(Filter filter, String pathSpec)
{
return filter == this.filter && pathSpec.equals(this.pathSpec);
}
public Filter getFilter() {
return filter;
}
public String getPathSpec() {
return pathSpec;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_web_Jetty9WebServer.java
|
1,722
|
{
@Override
public int compare( final String o1, final String o2 )
{
return o2.compareTo( o1 );
}
} );
| false
|
community_server_src_main_java_org_neo4j_server_web_Jetty9WebServer.java
|
1,723
|
public class Jetty9WebServer implements WebServer
{
private boolean wadlEnabled;
private Collection<InjectableProvider<?>> defaultInjectables;
private static class FilterDefinition
{
private final Filter filter;
private final String pathSpec;
public FilterDefinition(Filter filter, String pathSpec)
{
this.filter = filter;
this.pathSpec = pathSpec;
}
public boolean matches(Filter filter, String pathSpec)
{
return filter == this.filter && pathSpec.equals(this.pathSpec);
}
public Filter getFilter() {
return filter;
}
public String getPathSpec() {
return pathSpec;
}
}
private static final int MAX_THREADPOOL_SIZE = 640;
private static final int DEFAULT_HTTPS_PORT = 7473;
public static final int DEFAULT_PORT = 80;
public static final String DEFAULT_ADDRESS = "0.0.0.0";
private Server jetty;
private HandlerCollection handlers;
private int jettyHttpPort = DEFAULT_PORT;
private int jettyHttpsPort = DEFAULT_HTTPS_PORT;
private String jettyAddr = DEFAULT_ADDRESS;
private final HashMap<String, String> staticContent = new HashMap<>();
private final Map<String,JaxRsServletHolderFactory> jaxRSPackages =
new HashMap<>();
private final Map<String,JaxRsServletHolderFactory> jaxRSClasses =
new HashMap<>();
private final List<FilterDefinition> filters = new ArrayList<>();
private int jettyMaxThreads = Math.min(tenThreadsPerProcessor(), MAX_THREADPOOL_SIZE);
private boolean httpsEnabled = false;
private KeyStoreInformation httpsCertificateInformation = null;
private final SslSocketConnectorFactory sslSocketFactory = new SslSocketConnectorFactory();
private final HttpConnectorFactory connectorFactory = new HttpConnectorFactory();
private File requestLoggingConfiguration;
private final ConsoleLogger console;
private final StringLogger log;
public Jetty9WebServer( Logging logging )
{
this.console = logging.getConsoleLog( getClass() );
this.log = logging.getMessagesLog( getClass() );
}
@Override
public void init()
{
}
@Override
public void start()
{
if ( jetty == null )
{
QueuedThreadPool pool = createQueuedThreadPool(jettyMaxThreads);
jetty = new Server( pool );
jetty.addConnector( connectorFactory.createConnector( jetty, jettyAddr, jettyHttpPort, jettyMaxThreads ) );
if ( httpsEnabled )
{
if ( httpsCertificateInformation != null )
{
jetty.addConnector(
sslSocketFactory.createConnector( jetty, httpsCertificateInformation, jettyAddr, jettyHttpsPort, jettyMaxThreads ) );
}
else
{
throw new RuntimeException( "HTTPS set to enabled, but no HTTPS configuration provided." );
}
}
}
handlers = new HandlerList();
jetty.setHandler( handlers );
MovedContextHandler redirector = new MovedContextHandler();
handlers.addHandler( redirector );
loadAllMounts();
startJetty();
}
private QueuedThreadPool createQueuedThreadPool( int jettyMaxThreads )
{
// see: http://wiki.eclipse.org/Jetty/Howto/High_Load
int minThreads = Math.max( 2, jettyMaxThreads / 10 );
int maxCapacity = jettyMaxThreads * 1000 * 60; // threads * 1000 req/s * 60 s
BlockingQueue<Runnable> queue = new BlockingArrayQueue<>( minThreads, minThreads, maxCapacity );
int maxThreads = Math.max( jettyMaxThreads, minThreads );
return new QueuedThreadPool( maxThreads, minThreads , 60000, queue );
}
@Override
public void stop()
{
if ( jetty != null )
{
try
{
jetty.stop();
}
catch ( Exception e )
{
throw new RuntimeException( e );
}
try
{
jetty.join();
}
catch ( InterruptedException e )
{
log.info( "Interrupted while waiting for Jetty to stop." );
}
jetty = null;
}
}
@Override
public void setPort( int portNo )
{
jettyHttpPort = portNo;
}
@Override
public void setAddress( String addr )
{
jettyAddr = addr;
}
@Override
public void setMaxThreads( int maxThreads )
{
jettyMaxThreads = maxThreads;
}
@Override
public void addJAXRSPackages( List<String> packageNames, String mountPoint, Collection<Injectable<?>> injectables )
{
// We don't want absolute URIs at this point
mountPoint = ensureRelativeUri( mountPoint );
mountPoint = trimTrailingSlashToKeepJettyHappy( mountPoint );
JaxRsServletHolderFactory factory = jaxRSPackages.get( mountPoint );
if ( factory == null )
{
factory = new JaxRsServletHolderFactory.Packages();
jaxRSPackages.put( mountPoint, factory );
}
factory.add( packageNames, injectables );
log.debug( format( "Adding JAXRS packages %s at [%s]", packageNames, mountPoint ) );
}
@Override
public void addJAXRSClasses( List<String> classNames, String mountPoint, Collection<Injectable<?>> injectables )
{
// We don't want absolute URIs at this point
mountPoint = ensureRelativeUri( mountPoint );
mountPoint = trimTrailingSlashToKeepJettyHappy( mountPoint );
JaxRsServletHolderFactory factory = jaxRSClasses.get( mountPoint );
if ( factory == null )
{
factory = new JaxRsServletHolderFactory.Classes();
jaxRSClasses.put( mountPoint, factory );
}
factory.add( classNames, injectables );
log.debug( format( "Adding JAXRS classes %s at [%s]", classNames, mountPoint ) );
}
@Override
public void setWadlEnabled( boolean wadlEnabled )
{
this.wadlEnabled = wadlEnabled;
}
@Override
public void setDefaultInjectables( Collection<InjectableProvider<?>> defaultInjectables )
{
this.defaultInjectables = defaultInjectables;
}
@Override
public void removeJAXRSPackages( List<String> packageNames, String serverMountPoint )
{
JaxRsServletHolderFactory factory = jaxRSPackages.get( serverMountPoint );
if ( factory != null )
{
factory.remove( packageNames );
}
}
@Override
public void removeJAXRSClasses( List<String> classNames, String serverMountPoint )
{
JaxRsServletHolderFactory factory = jaxRSClasses.get( serverMountPoint );
if ( factory != null )
{
factory.remove( classNames );
}
}
@Override
public void addFilter(Filter filter, String pathSpec)
{
filters.add( new FilterDefinition( filter, pathSpec ) );
}
@Override
public void removeFilter(Filter filter, String pathSpec)
{
Iterator<FilterDefinition> iter = filters.iterator();
while(iter.hasNext())
{
FilterDefinition current = iter.next();
if(current.matches(filter, pathSpec))
{
iter.remove();
}
}
}
@Override
public void addStaticContent( String contentLocation, String serverMountPoint )
{
staticContent.put( serverMountPoint, contentLocation );
}
@Override
public void removeStaticContent( String contentLocation, String serverMountPoint )
{
staticContent.remove( serverMountPoint );
}
@Override
public void invokeDirectly( String targetPath, HttpServletRequest request, HttpServletResponse response )
throws IOException, ServletException
{
jetty.handle( targetPath, (Request) request, request, response );
}
@Override
public void setHttpLoggingConfiguration( File logbackConfigFile )
{
this.requestLoggingConfiguration = logbackConfigFile;
}
@Override
public void setEnableHttps( boolean enable )
{
httpsEnabled = enable;
}
@Override
public void setHttpsPort( int portNo )
{
jettyHttpsPort = portNo;
}
@Override
public void setHttpsCertificateInformation( KeyStoreInformation config )
{
httpsCertificateInformation = config;
}
public Server getJetty()
{
return jetty;
}
protected void startJetty()
{
try
{
jetty.start();
}
catch ( Exception e )
{
throw new RuntimeException( e );
}
}
private int tenThreadsPerProcessor()
{
return 10 * Runtime.getRuntime()
.availableProcessors();
}
private void loadAllMounts()
{
SessionManager sm = new HashSessionManager();
final SortedSet<String> mountpoints = new TreeSet<>( new Comparator<String>()
{
@Override
public int compare( final String o1, final String o2 )
{
return o2.compareTo( o1 );
}
} );
mountpoints.addAll( staticContent.keySet() );
mountpoints.addAll( jaxRSPackages.keySet() );
mountpoints.addAll( jaxRSClasses.keySet() );
for ( String contentKey : mountpoints )
{
final boolean isStatic = staticContent.containsKey( contentKey );
final boolean isJaxrsPackage = jaxRSPackages.containsKey( contentKey );
final boolean isJaxrsClass = jaxRSClasses.containsKey( contentKey );
if ( countSet( isStatic, isJaxrsPackage, isJaxrsClass ) > 1 )
{
throw new RuntimeException(
format( "content-key '%s' is mapped more than once", contentKey ) );
}
else if ( isStatic )
{
loadStaticContent( sm, contentKey );
}
else if ( isJaxrsPackage )
{
loadJAXRSPackage( sm, contentKey );
}
else if ( isJaxrsClass )
{
loadJAXRSClasses( sm, contentKey );
}
else
{
throw new RuntimeException( format( "content-key '%s' is not mapped", contentKey ) );
}
}
if( requestLoggingConfiguration != null )
{
loadRequestLogging();
}
}
private int countSet( boolean... booleans )
{
int count = 0;
for ( boolean bool : booleans )
{
if ( bool )
{
count++;
}
}
return count;
}
private void loadRequestLogging() {
final RequestLogImpl requestLog = new RequestLogImpl();
requestLog.setFileName( requestLoggingConfiguration.getAbsolutePath() );
final RequestLogHandler requestLogHandler = new RequestLogHandler();
requestLogHandler.setRequestLog( requestLog );
handlers.addHandler( requestLogHandler );
}
private String trimTrailingSlashToKeepJettyHappy( String mountPoint )
{
if ( mountPoint.equals( "/" ) )
{
return mountPoint;
}
if ( mountPoint.endsWith( "/" ) )
{
mountPoint = mountPoint.substring( 0, mountPoint.length() - 1 );
}
return mountPoint;
}
private String ensureRelativeUri( String mountPoint )
{
try
{
URI result = new URI( mountPoint );
if ( result.isAbsolute() )
{
return result.getPath();
}
else
{
return result.toString();
}
}
catch ( URISyntaxException e )
{
log.debug( format( "Unable to translate [%s] to a relative URI in ensureRelativeUri(String mountPoint)",
mountPoint ) );
return mountPoint;
}
}
private void loadStaticContent( SessionManager sm, String mountPoint )
{
String contentLocation = staticContent.get( mountPoint );
console.log( "Mounting static content at [%s] from [%s]", mountPoint, contentLocation );
try
{
SessionHandler sessionHandler = new SessionHandler( sm );
sessionHandler.setServer( getJetty() );
final WebAppContext staticContext = new WebAppContext();
staticContext.setServer( getJetty() );
staticContext.setContextPath( mountPoint );
staticContext.setSessionHandler( sessionHandler );
URL resourceLoc = getClass().getClassLoader()
.getResource( contentLocation );
if ( resourceLoc != null )
{
log.debug( format( "Found [%s]", resourceLoc ) );
URL url = resourceLoc.toURI().toURL();
final Resource resource = Resource.newResource( url );
staticContext.setBaseResource( resource );
log.debug( format( "Mounting static content from [%s] at [%s]", url, mountPoint ) );
addFiltersTo(staticContext);
handlers.addHandler( staticContext );
}
else
{
console.log(
"No static content available for Neo Server at port [%d], management console may not be available.",
jettyHttpPort );
}
}
catch ( Exception e )
{
console.error( "Unknown error loading static content", e );
e.printStackTrace();
throw new RuntimeException( e );
}
}
private void loadJAXRSPackage( SessionManager sm, String mountPoint )
{
loadJAXRSResource( sm, mountPoint, jaxRSPackages.get( mountPoint ) );
}
private void loadJAXRSClasses( SessionManager sm, String mountPoint )
{
loadJAXRSResource( sm, mountPoint, jaxRSClasses.get( mountPoint ) );
}
private void loadJAXRSResource( SessionManager sm, String mountPoint,
JaxRsServletHolderFactory jaxRsServletHolderFactory )
{
SessionHandler sessionHandler = new SessionHandler( sm );
sessionHandler.setServer( getJetty() );
log.debug( format( "Mounting servlet at [%s]", mountPoint ) );
ServletContextHandler jerseyContext = new ServletContextHandler();
jerseyContext.setServer( getJetty() );
jerseyContext.setErrorHandler( new NeoJettyErrorHandler() );
jerseyContext.setContextPath( mountPoint );
jerseyContext.setSessionHandler( sessionHandler );
jerseyContext.addServlet( jaxRsServletHolderFactory.create( defaultInjectables, wadlEnabled ), "/*" );
addFiltersTo(jerseyContext);
handlers.addHandler(jerseyContext);
}
private void addFiltersTo(ServletContextHandler context) {
for(FilterDefinition filterDef : filters)
{
context.addFilter( new FilterHolder(
filterDef.getFilter() ),
filterDef.getPathSpec(), EnumSet.allOf(DispatcherType.class) );
}
}
}
| false
|
community_server_src_main_java_org_neo4j_server_web_Jetty9WebServer.java
|
1,724
|
public static class Packages extends JaxRsServletHolderFactory
{
@Override
protected void configure( ServletHolder servletHolder, String packages )
{
servletHolder.setInitParameter( PackagesResourceConfig.PROPERTY_PACKAGES, packages );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_web_JaxRsServletHolderFactory.java
|
1,725
|
public static class Classes extends JaxRsServletHolderFactory
{
@Override
protected void configure( ServletHolder servletHolder, String classes )
{
servletHolder.setInitParameter( ClassNamesResourceConfig.PROPERTY_CLASSNAMES, classes );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_web_JaxRsServletHolderFactory.java
|
1,726
|
public abstract class JaxRsServletHolderFactory
{
private final List<String> items = new ArrayList<String>();
private final List<Injectable<?>> injectables = new ArrayList<Injectable<?>>();
public void add( List<String> items, Collection<Injectable<?>> injectableProviders )
{
this.items.addAll( items );
if ( injectableProviders != null )
{
this.injectables.addAll( injectableProviders );
}
}
public void remove( List<String> items )
{
this.items.removeAll( items );
}
public ServletHolder create( Collection<InjectableProvider<?>> defaultInjectables, boolean wadlEnabled )
{
Collection<InjectableProvider<?>> injectableProviders = mergeInjectables( defaultInjectables, injectables );
ServletContainer container = new NeoServletContainer( injectableProviders );
ServletHolder servletHolder = new ServletHolder( container );
servletHolder.setInitParameter( ResourceConfig.FEATURE_DISABLE_WADL, String.valueOf( !wadlEnabled ) );
configure( servletHolder, toCommaSeparatedList( items ) );
servletHolder.setInitParameter( ResourceConfig.PROPERTY_CONTAINER_RESPONSE_FILTERS, AllowAjaxFilter.class.getName() );
servletHolder.setInitParameter( ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS, CollectUserAgentFilter.class.getName() );
return servletHolder;
}
protected abstract void configure( ServletHolder servletHolder, String commaSeparatedList );
private Collection<InjectableProvider<?>> mergeInjectables( Collection<InjectableProvider<?>> defaultInjectables,
Collection<Injectable<?>> injectables )
{
Collection<InjectableProvider<?>> injectableProviders = new ArrayList<InjectableProvider<?>>();
if ( defaultInjectables != null )
{
injectableProviders.addAll( defaultInjectables );
}
if ( injectables != null )
{
for ( Injectable<?> injectable : injectables )
{
injectableProviders.add( new InjectableWrapper( injectable ) );
}
}
return injectableProviders;
}
private String toCommaSeparatedList( List<String> packageNames )
{
StringBuilder sb = new StringBuilder();
for ( String str : packageNames )
{
sb.append( str );
sb.append( ", " );
}
String result = sb.toString();
return result.substring( 0, result.length() - 2 );
}
public static class Packages extends JaxRsServletHolderFactory
{
@Override
protected void configure( ServletHolder servletHolder, String packages )
{
servletHolder.setInitParameter( PackagesResourceConfig.PROPERTY_PACKAGES, packages );
}
}
public static class Classes extends JaxRsServletHolderFactory
{
@Override
protected void configure( ServletHolder servletHolder, String classes )
{
servletHolder.setInitParameter( ClassNamesResourceConfig.PROPERTY_CLASSNAMES, classes );
}
}
}
| false
|
community_server_src_main_java_org_neo4j_server_web_JaxRsServletHolderFactory.java
|
1,727
|
@Provider
public class InjectableWrapper extends InjectableProvider<Object>
{
private final Injectable injectable;
public InjectableWrapper( Injectable injectable )
{
super( injectable.getType() );
this.injectable = injectable;
}
@Override
public Object getValue( HttpContext c )
{
return injectable.getValue();
}
}
| false
|
community_server_src_main_java_org_neo4j_server_web_InjectableWrapper.java
|
1,728
|
public class HttpHeaderUtils {
private static final String UTF8 = "UTF-8";
public static final Map<String, String> CHARSET = Collections.singletonMap("charset", UTF8);
public static MediaType mediaTypeWithCharsetUtf8(String mediaType)
{
return new MediaType(mediaType, null, CHARSET);
}
public static MediaType mediaTypeWithCharsetUtf8(MediaType mediaType)
{
Map<String, String> parameters = mediaType.getParameters();
if (parameters.isEmpty())
{
return new MediaType(mediaType.getType(), mediaType.getSubtype(), CHARSET);
}
if (parameters.containsKey("charset"))
{
return mediaType;
}
Map<String, String> paramsWithCharset = new HashMap<String, String>(parameters);
paramsWithCharset.putAll(CHARSET);
return new MediaType(mediaType.getType(), mediaType.getSubtype(), paramsWithCharset);
}
}
| false
|
community_server_src_main_java_org_neo4j_server_web_HttpHeaderUtils.java
|
1,729
|
public class HttpConnectorFactory
{
public ConnectionFactory createHttpConnectionFactory()
{
HttpConfiguration httpConfig = new HttpConfiguration();
httpConfig.setRequestHeaderSize( 20 * 1024 );
httpConfig.setResponseHeaderSize( 20 * 1024 );
return new HttpConnectionFactory( httpConfig );
}
public ServerConnector createConnector( Server server, String host, int port, int jettyMaxThreads )
{
ConnectionFactory httpFactory = createHttpConnectionFactory();
return createConnector(server, host, port, jettyMaxThreads, httpFactory );
}
public ServerConnector createConnector( Server server, String host, int port, int jettyMaxThreads, ConnectionFactory... httpFactories )
{
// Note: 1/4 accept, 3/4 select
int availableProcessors = Runtime.getRuntime().availableProcessors();
int cpusByConfiguredThreads = jettyMaxThreads / 10;
int cpusToConsider = Math.max(1, Math.min( availableProcessors, cpusByConfiguredThreads ) );
int acceptors = Math.max( 1 ,cpusToConsider / 4 );
int selectors = Math.max( 1, cpusToConsider - acceptors );
ServerConnector connector = new ServerConnector( server , null, null, null, acceptors, selectors, httpFactories );
connector.setConnectionFactories( Arrays.asList( httpFactories ) );
// TCP backlog, per socket, 50 is the default, consider adapting if needed
connector.setAcceptQueueSize( 50 );
connector.setHost( host );
connector.setPort( port );
return connector;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_web_HttpConnectorFactory.java
|
1,730
|
public class JavascriptExecutor implements ScriptExecutor
{
private final Scriptable prototype;
private final Script compiledScript;
public static class Factory implements ScriptExecutor.Factory
{
/**
* Note that you can set sandbox/no sandbox once, after that it is globally defined
* for the JVM. If you create a new factory with a different sandboxing setting, an
* exception will be thrown.
*
* @param enableSandboxing
*/
public Factory(boolean enableSandboxing)
{
if(enableSandboxing)
{
GlobalJavascriptInitializer.initialize( GlobalJavascriptInitializer.Mode.SANDBOXED );
} else
{
GlobalJavascriptInitializer.initialize( GlobalJavascriptInitializer.Mode.UNSAFE );
}
}
@Override
public ScriptExecutor createExecutorForScript( String script ) throws EvaluationException
{
return new JavascriptExecutor( script );
}
}
public JavascriptExecutor( String script )
{
Context cx = Context.enter();
try
{
prototype = createPrototype(cx);
compiledScript = cx.compileString( script, "Unknown", 0, null );
} finally
{
Context.exit();
}
}
private Scriptable createPrototype( Context cx )
{
Scriptable proto = cx.initStandardObjects();
Scriptable topLevel = new ImporterTopLevel(cx);
proto.setParentScope( topLevel );
return proto;
}
@Override
public Object execute( Map<String, Object> variables ) throws EvaluationException
{
Context cx = Context.enter();
try
{
Scriptable scope = cx.newObject(prototype);
scope.setPrototype(prototype);
if(variables != null)
{
for(String k : variables.keySet())
{
scope.put( k, scope, variables.get( k ) );
}
}
Object out = compiledScript.exec( cx, scope );
if(out instanceof NativeJavaObject)
{
return ((NativeJavaObject)out).unwrap();
} else if(out instanceof Undefined )
{
return null;
} else
{
return out;
}
} catch( RhinoException e )
{
throw new EvaluationException( "Failed to execute script, see nested exception.", e );
} finally
{
Context.exit();
}
}
}
| false
|
community_server_src_main_java_org_neo4j_server_scripting_javascript_JavascriptExecutor.java
|
1,731
|
{
protected Context makeContext()
{
Context cx = super.makeContext();
cx.setLanguageVersion( Context.VERSION_1_7 );
// TODO: This goes up to 9, do performance tests to determine appropriate level of optimization
cx.setOptimizationLevel( 4 );
return cx;
}
};
| false
|
community_server_src_main_java_org_neo4j_server_scripting_javascript_GlobalJavascriptInitializer.java
|
1,732
|
{
public boolean evaluate()
{
return occursIn( query, new File( logDirectory, "http.log" ) );
}
} );
| false
|
community_server_src_test_java_org_neo4j_server_web_logging_HTTPLoggingDocIT.java
|
1,733
|
private static class NullJobScheduler implements JobScheduler
{
@Override
public void scheduleAtFixedRate( Runnable job, String name, long delay, long period )
{
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rrd_RrdFactoryTest.java
|
1,734
|
{
@Override
public RrdDb get()
{
return db;
}
@Override
public void close() throws IOException
{
try
{
db.close();
}
finally
{
new File( db.getPath() ).delete();
}
}
};
| false
|
community_server_src_main_java_org_neo4j_server_rrd_RrdFactory.java
|
1,735
|
{
@Override
public void run()
{
try
{
FileUtils.deleteRecursively(tempFile);
}
catch ( IOException e )
{
// Ignore
}
}
});
| false
|
community_server_src_main_java_org_neo4j_server_rrd_RrdFactory.java
|
1,736
|
public class RrdFactory
{
public static final int STEP_SIZE = 1;
private static final String RRD_THREAD_NAME = "Statistics Gatherer";
private final Configuration config;
private final ConsoleLogger log;
public RrdFactory( Configuration config, Logging logging )
{
this.config = config;
this.log = logging.getConsoleLog( getClass() );
}
public org.neo4j.server.database.RrdDbWrapper createRrdDbAndSampler( final Database db, JobScheduler scheduler ) throws IOException
{
NodeManager nodeManager = db.getGraph().getDependencyResolver().resolveDependency( NodeManager.class );
Sampleable[] primitives = {
new NodeIdsInUseSampleable( nodeManager ),
new PropertyCountSampleable( nodeManager ),
new RelationshipCountSampleable( nodeManager )
};
Sampleable[] usage = {};
final String rrdPath = config.getString( RRDB_LOCATION_PROPERTY_KEY,
getDefaultRrdFile( db.getGraph() ) );
final RrdDbWrapper rrdb = createRrdb( rrdPath, isEphemereal( db.getGraph() ), join( primitives, usage ) );
scheduler.scheduleAtFixedRate(
new RrdJob( new RrdSamplerImpl( rrdb.get(), primitives ) ),
RRD_THREAD_NAME + "[primitives]",
SECONDS.toMillis( 0 ),
SECONDS.toMillis( 3 )
);
return rrdb;
}
private Sampleable[] join( Sampleable[]... sampleables )
{
ArrayList<Sampleable> result = new ArrayList<Sampleable>();
for ( Sampleable[] sampleable : sampleables )
{
Collections.addAll( result, sampleable );
}
return result.toArray( new Sampleable[result.size()] );
}
private String getDefaultRrdFile( GraphDatabaseAPI db ) throws IOException
{
return isEphemereal( db ) ? tempRrdFile() : new File( db.getStoreDir(), "rrd" ).getAbsolutePath();
}
protected String tempRrdFile() throws IOException
{
final File tempFile = File.createTempFile( "neo4j", "rrd" );
tempFile.delete();
tempFile.mkdir();
Runtime.getRuntime().addShutdownHook( new Thread()
{
@Override
public void run()
{
try
{
FileUtils.deleteRecursively(tempFile);
}
catch ( IOException e )
{
// Ignore
}
}
});
return tempFile.getAbsolutePath();
}
private boolean isEphemereal( GraphDatabaseAPI db )
{
Config config = db.getDependencyResolver().resolveDependency( Config.class );
if ( config == null )
{
return false;
}
else
{
Boolean ephemeral = config.get( InternalAbstractGraphDatabase.Configuration.ephemeral );
return ephemeral != null && ephemeral;
}
}
protected RrdDbWrapper createRrdb( String rrdPathx, boolean ephemeral, Sampleable... sampleables )
{
File rrdFile = new File( rrdPathx );
if ( rrdFile.exists() )
{
try
{
if ( !validateStepSize( rrdFile ) )
{
return recreateArchive( rrdFile, ephemeral, sampleables );
}
Sampleable[] missing = checkDataSources( rrdFile.getAbsolutePath(), sampleables );
if ( missing.length > 0 )
{
updateDataSources( rrdFile.getAbsolutePath(), missing );
}
return wrap( new RrdDb( rrdFile.getAbsolutePath() ), ephemeral );
}
catch ( IOException e )
{
// RRD file may have become corrupt
log.error( "Unable to open rrd store, attempting to recreate it", e );
return recreateArchive( rrdFile, ephemeral, sampleables );
}
catch ( IllegalArgumentException e )
{
// RRD file may have become corrupt
log.error( "Unable to open rrd store, attempting to recreate it", e );
return recreateArchive( rrdFile, ephemeral, sampleables );
}
}
else
{
RrdDef rrdDef = new RrdDef( rrdFile.getAbsolutePath(), STEP_SIZE );
defineDataSources( rrdDef, sampleables );
addArchives( rrdDef );
try
{
return wrap( new RrdDb( rrdDef ), ephemeral );
}
catch ( IOException e )
{
log.error( "Unable to create new rrd store", e );
throw new RuntimeException( e );
}
}
}
private RrdDbWrapper wrap( RrdDb db, boolean ephemeral ) throws IOException
{
return ephemeral ? cleaningRrdDb( db ) : new RrdDbWrapper.Plain( db );
}
private RrdDbWrapper cleaningRrdDb( final RrdDb db )
{
return new RrdDbWrapper()
{
@Override
public RrdDb get()
{
return db;
}
@Override
public void close() throws IOException
{
try
{
db.close();
}
finally
{
new File( db.getPath() ).delete();
}
}
};
}
private boolean validateStepSize( File rrdFile ) throws IOException
{
RrdDb r = null;
try
{
r = new RrdDb( rrdFile.getAbsolutePath(), true );
return ( r.getRrdDef().getStep() == STEP_SIZE );
}
finally
{
if( r != null )
{
r.close();
}
}
}
private RrdDbWrapper recreateArchive( File rrdFile, boolean ephemeral, Sampleable[] sampleables )
{
File file = new File( rrdFile.getParentFile(),
rrdFile.getName() + "-invalid-" + System.currentTimeMillis() );
if ( rrdFile.renameTo( file ) )
{
log.error( "current RRDB is invalid, renamed it to %s", file.getAbsolutePath() );
return createRrdb( rrdFile.getAbsolutePath(), ephemeral, sampleables );
}
throw new RuntimeException( "RRD file ['" + rrdFile.getAbsolutePath()
+ "'] is invalid, but I do not have write permissions to recreate it." );
}
private static Sampleable[] checkDataSources( String rrdPath, Sampleable[] sampleables ) throws IOException
{
RrdDb rrdDb = new RrdDb( rrdPath, true );
List<Sampleable> missing = new ArrayList<Sampleable>();
for ( Sampleable sampleable : sampleables )
{
if ( rrdDb.getDatasource( sampleable.getName() ) == null )
{
missing.add( sampleable );
}
}
rrdDb.close();
return missing.toArray( new Sampleable[missing.size()] );
}
private void updateDataSources( String rrdPath, Sampleable[] sampleables ) throws IOException
{
for ( Sampleable sampleable : sampleables )
{
log.warn( "Updating RRDB structure, adding: " + sampleable.getName() );
RrdToolkit.addDatasource( rrdPath, createDsDef( sampleable ), true );
}
}
private static DsDef createDsDef( Sampleable sampleable )
{
return new DsDef( sampleable.getName(), sampleable.getType(),
120 * STEP_SIZE, NaN, NaN );
}
private void addArchives( RrdDef rrdDef )
{
for ( ConsolFun fun : asList( AVERAGE, MAX, MIN ) )
{
addArchive( rrdDef, fun, MINUTES.toSeconds( 30 ), SECONDS.toSeconds( 1 ) );
addArchive( rrdDef, fun, DAYS.toSeconds( 1 ), MINUTES.toSeconds( 1 ) );
addArchive( rrdDef, fun, DAYS.toSeconds( 7 ), MINUTES.toSeconds( 5 ) );
addArchive( rrdDef, fun, DAYS.toSeconds( 30 ), MINUTES.toSeconds( 30 ) );
addArchive( rrdDef, fun, DAYS.toSeconds( 1780 ), HOURS.toSeconds( 2 ) );
}
}
private void addArchive( RrdDef rrdDef, ConsolFun fun, long length, long resolution )
{
rrdDef.addArchive( fun, 0.2,
(int) ( resolution * STEP_SIZE ),
(int) ( length / ( resolution * STEP_SIZE ) ) );
}
private void defineDataSources( RrdDef rrdDef, Sampleable[] sampleables )
{
for ( Sampleable sampleable : sampleables )
{
rrdDef.addDatasource( createDsDef( sampleable ) );
}
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rrd_RrdFactory.java
|
1,737
|
@Provider
public class RrdDbProvider extends InjectableProvider<RrdDb>
{
private final RrdDbWrapper rrdDbWrapper;
public RrdDbProvider( RrdDbWrapper rrdDbWrapper )
{
super( RrdDb.class );
this.rrdDbWrapper = rrdDbWrapper;
}
@Override
public RrdDb getValue( HttpContext c )
{
return rrdDbWrapper.get();
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rrd_RrdDbProvider.java
|
1,738
|
public class RelationshipCountSampleableTest
{
public GraphDatabaseAPI db;
public RelationshipCountSampleable sampleable;
@Test
public void emptyDbHasZeroRelationships()
{
assertThat( sampleable.getValue(), is( 0d ) );
}
@Test
public void addANodeAndSampleableGoesUp()
{
createARelationship( db );
assertThat( sampleable.getValue(), is( 1d ) );
}
private void createARelationship( GraphDatabaseAPI db )
{
Transaction tx = db.beginTx();
Node node1 = db.createNode();
Node node2 = db.createNode();
node1.createRelationshipTo( node2, withName( "friend" ) );
tx.success();
tx.finish();
}
@Before
public void setUp() throws Exception
{
db = (GraphDatabaseAPI)new TestGraphDatabaseFactory().newImpermanentDatabase();
sampleable = new RelationshipCountSampleable( db.getDependencyResolver().resolveDependency( NodeManager.class ) );
}
@After
public void shutdownDatabase()
{
this.db.shutdown();
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rrd_RelationshipCountSampleableTest.java
|
1,739
|
{
@Override
public String name()
{
return "knows_about";
}
} );
| false
|
community_server_src_test_java_org_neo4j_server_rrd_PropertyCountSampleableTest.java
|
1,740
|
public class PropertyCountSampleableTest
{
public Database db;
public PropertyCountSampleable sampleable;
public long referenceNodeId;
@Before
public void setupReferenceNode()
{
db = new WrappedDatabase( (AbstractGraphDatabase) new TestGraphDatabaseFactory().newImpermanentDatabase() );
DependencyResolver dependencyResolver = db.getGraph().getDependencyResolver();
sampleable = new PropertyCountSampleable( dependencyResolver.resolveDependency( NodeManager.class ) );
Transaction tx = db.getGraph().beginTx();
referenceNodeId = db.getGraph().createNode().getId();
tx.success();
tx.finish();
}
@Test
public void emptyDbHasZeroNodesInUse()
{
assertThat( sampleable.getValue(), is( 0d ) );
}
@Test
public void addANodeAndSampleableGoesUp()
{
addPropertyToReferenceNode();
assertThat( sampleable.getValue(), is( 1d ) );
addNodeIntoGraph();
addNodeIntoGraph();
assertThat( sampleable.getValue(), is( 3d ) );
}
private void addNodeIntoGraph()
{
Transaction tx = db.getGraph().beginTx();
Node referenceNode = db.getGraph().getNodeById( referenceNodeId );
Node myNewNode = db.getGraph().createNode();
myNewNode.setProperty( "id", UUID.randomUUID().toString() );
myNewNode.createRelationshipTo( referenceNode, new RelationshipType()
{
@Override
public String name()
{
return "knows_about";
}
} );
tx.success();
tx.finish();
}
private void addPropertyToReferenceNode()
{
Transaction tx = db.getGraph().beginTx();
Node n = db.getGraph().getNodeById( referenceNodeId );
n.setProperty( "monkey", "rock!" );
tx.success();
tx.finish();
}
@After
public void shutdownDatabase() throws Throwable
{
db.getGraph().shutdown();
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rrd_PropertyCountSampleableTest.java
|
1,741
|
public class NodeIdsInUseSampleableTest
{
public GraphDatabaseAPI db;
public NodeIdsInUseSampleable sampleable;
@Test
public void emptyDbHasZeroNodesInUse()
{
assertThat( sampleable.getValue(), is( 0d ) );
}
@Test
public void addANodeAndSampleableGoesUp()
{
double oldValue = sampleable.getValue();
createNode( db );
assertThat( sampleable.getValue(), greaterThan( oldValue ) );
}
private void createNode( GraphDatabaseAPI db )
{
Transaction tx = db.beginTx();
db.createNode();
tx.success();
tx.finish();
}
@Before
public void setUp() throws Exception
{
db = (GraphDatabaseAPI) new TestGraphDatabaseFactory().newImpermanentDatabase();
DependencyResolver dependencyResolver = db.getDependencyResolver();
sampleable = new NodeIdsInUseSampleable( dependencyResolver.resolveDependency( NodeManager.class ) );
}
@After
public void shutdown() throws Throwable
{
db.shutdown();
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rrd_NodeIdsInUseSampleableTest.java
|
1,742
|
public class MemoryUsedSampleableTest
{
MemoryUsedSampleable sampleable;
@Before
public void setUp() throws Exception
{
sampleable = new MemoryUsedSampleable();
}
@Test
public void memoryUsageIsBetweenZeroAndOneHundred()
{
assertThat( sampleable.getValue(), greaterThan( 0d ) );
assertThat( sampleable.getValue(), lessThan( 100d ) );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rrd_MemoryUsedSampleableTest.java
|
1,743
|
public class DatabasePrimitivesSampleableBaseDocTest
{
@Test
public void sampleTest() throws MalformedObjectNameException, IOException
{
GraphDatabaseAPI db = (GraphDatabaseAPI)new TestGraphDatabaseFactory().newImpermanentDatabase();
DatabasePrimitivesSampleableBase sampleable = new NodeIdsInUseSampleable( nodeManager( db ) );
assertTrue( "There should be no nodes in use.", sampleable.getValue() == 0 );
db.shutdown();
}
@Test
public void rrd_uses_temp_dir() throws Exception
{
GraphDatabaseAPI db = (GraphDatabaseAPI)new TestGraphDatabaseFactory().newImpermanentDatabase();
DatabasePrimitivesSampleableBase sampleable = new NodeIdsInUseSampleable( nodeManager( db ) );
assertTrue( "There should be no nodes in use.", sampleable.getValue() == 0 );
db.shutdown();
}
private NodeManager nodeManager( GraphDatabaseAPI db )
{
return db.getDependencyResolver().resolveDependency( NodeManager.class );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rrd_DatabasePrimitivesSampleableBaseDocTest.java
|
1,744
|
public class WebHelper
{
private final URI baseUri;
private final GraphDbHelper helper;
public WebHelper( URI baseUri, Database database )
{
this.baseUri = baseUri;
this.helper = new GraphDbHelper( database );
}
public URI createNode()
{
long nodeId = helper.createNode();
try
{
return new URI( baseUri.toString() + "/" + nodeId );
}
catch ( URISyntaxException e )
{
throw new RuntimeException( e );
}
}
public URI createNodeWithProperties( Map<String, Object> props )
{
URI nodeUri = createNode();
setNodeProperties( nodeUri, props );
return nodeUri;
}
private void setNodeProperties( URI nodeUri, Map<String, Object> props )
{
helper.setNodeProperties( extractNodeId( nodeUri ), props );
}
private long extractNodeId( URI nodeUri )
{
String path = nodeUri.getPath();
if ( path.startsWith( "/" ) )
{
path = path.substring( 1 );
}
return Long.parseLong( path );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_web_WebHelper.java
|
1,745
|
public static class TransactionUriBuilder implements TransactionUriScheme
{
private final UriInfo uriInfo;
public TransactionUriBuilder( UriInfo uriInfo )
{
this.uriInfo = uriInfo;
}
@Override
public URI txUri( long id )
{
return builder( id ).build();
}
@Override
public URI txCommitUri( long id )
{
return builder( id ).path( "/commit" ).build();
}
private UriBuilder builder( long id )
{
return uriInfo.getBaseUriBuilder().path( TransactionalService.class ).path( "/" + id );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_web_TransactionalService.java
|
1,746
|
{
@Override
public void write( OutputStream output ) throws IOException, WebApplicationException
{
ExecutionResultSerializer serializer = facade.serializer( output );
serializer.errors( asList( neo4jError ) );
serializer.finish();
}
};
| false
|
community_server_src_main_java_org_neo4j_server_rest_web_TransactionalService.java
|
1,747
|
{
@Override
public void write( OutputStream output ) throws IOException, WebApplicationException
{
transactionHandle.rollback( facade.serializer( output ) );
}
};
| false
|
community_server_src_main_java_org_neo4j_server_rest_web_TransactionalService.java
|
1,748
|
{
@Override
public void write( OutputStream output ) throws IOException, WebApplicationException
{
transactionHandle.commit( facade.deserializer( input ), facade.serializer( output ) );
}
};
| false
|
community_server_src_main_java_org_neo4j_server_rest_web_TransactionalService.java
|
1,749
|
{
@Override
public void write( OutputStream output ) throws IOException, WebApplicationException
{
transactionHandle.execute( facade.deserializer( input ), facade.serializer( output ) );
}
};
| false
|
community_server_src_main_java_org_neo4j_server_rest_web_TransactionalService.java
|
1,750
|
@Path("/transaction")
public class TransactionalService
{
private final TransactionFacade facade;
private final TransactionUriScheme uriScheme;
public TransactionalService( @Context TransactionFacade facade, @Context UriInfo uriInfo )
{
this.facade = facade;
this.uriScheme = new TransactionUriBuilder( uriInfo );
}
@POST
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response executeStatementsInNewTransaction( final InputStream input )
{
try
{
TransactionHandle transactionHandle = facade.newTransactionHandle( uriScheme );
return createdResponse( transactionHandle, executeStatements( input, transactionHandle ) );
}
catch ( TransactionLifecycleException e )
{
return invalidTransaction( e );
}
}
@POST
@Path("/{id}")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response executeStatements( @PathParam("id") final long id, final InputStream input )
{
final TransactionHandle transactionHandle;
try
{
transactionHandle = facade.findTransactionHandle( id );
}
catch ( TransactionLifecycleException e )
{
return invalidTransaction( e );
}
return okResponse( executeStatements( input, transactionHandle ) );
}
@POST
@Path("/{id}/commit")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response commitTransaction( @PathParam("id") final long id, final InputStream input )
{
final TransactionHandle transactionHandle;
try
{
transactionHandle = facade.findTransactionHandle( id );
}
catch ( TransactionLifecycleException e )
{
return invalidTransaction( e );
}
return okResponse( executeStatementsAndCommit( input, transactionHandle ) );
}
@POST
@Path("/commit")
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response commitNewTransaction( final InputStream input )
{
final TransactionHandle transactionHandle;
try
{
transactionHandle = facade.newTransactionHandle( uriScheme );
}
catch ( TransactionLifecycleException e )
{
return invalidTransaction( e );
}
return okResponse( executeStatementsAndCommit( input, transactionHandle ) );
}
@DELETE
@Path("/{id}")
@Consumes({MediaType.APPLICATION_JSON})
public Response rollbackTransaction( @PathParam("id") final long id )
{
final TransactionHandle transactionHandle;
try
{
transactionHandle = facade.findTransactionHandle( id );
}
catch ( TransactionLifecycleException e )
{
return invalidTransaction( e );
}
return okResponse( rollback( transactionHandle ) );
}
private Response invalidTransaction( TransactionLifecycleException e )
{
return Response.status( Response.Status.NOT_FOUND )
.entity( serializeError( e.toNeo4jError() ) )
.build();
}
private Response createdResponse( TransactionHandle transactionHandle, StreamingOutput streamingResults )
{
return Response.created( transactionHandle.uri() )
.entity( streamingResults )
.build();
}
private Response okResponse( StreamingOutput streamingResults )
{
return Response.ok()
.entity( streamingResults )
.build();
}
private StreamingOutput executeStatements( final InputStream input, final TransactionHandle transactionHandle )
{
return new StreamingOutput()
{
@Override
public void write( OutputStream output ) throws IOException, WebApplicationException
{
transactionHandle.execute( facade.deserializer( input ), facade.serializer( output ) );
}
};
}
private StreamingOutput executeStatementsAndCommit( final InputStream input, final TransactionHandle transactionHandle )
{
return new StreamingOutput()
{
@Override
public void write( OutputStream output ) throws IOException, WebApplicationException
{
transactionHandle.commit( facade.deserializer( input ), facade.serializer( output ) );
}
};
}
private StreamingOutput rollback( final TransactionHandle transactionHandle )
{
return new StreamingOutput()
{
@Override
public void write( OutputStream output ) throws IOException, WebApplicationException
{
transactionHandle.rollback( facade.serializer( output ) );
}
};
}
private StreamingOutput serializeError( final Neo4jError neo4jError )
{
return new StreamingOutput()
{
@Override
public void write( OutputStream output ) throws IOException, WebApplicationException
{
ExecutionResultSerializer serializer = facade.serializer( output );
serializer.errors( asList( neo4jError ) );
serializer.finish();
}
};
}
public static class TransactionUriBuilder implements TransactionUriScheme
{
private final UriInfo uriInfo;
public TransactionUriBuilder( UriInfo uriInfo )
{
this.uriInfo = uriInfo;
}
@Override
public URI txUri( long id )
{
return builder( id ).build();
}
@Override
public URI txCommitUri( long id )
{
return builder( id ).path( "/commit" ).build();
}
private UriBuilder builder( long id )
{
return uriInfo.getBaseUriBuilder().path( TransactionalService.class ).path( "/" + id );
}
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rest_web_TransactionalService.java
|
1,751
|
public class TransactionWrappingRestfulGraphDatabase extends RestfulGraphDatabase
{
private final AbstractGraphDatabase graph;
private final RestfulGraphDatabase restfulGraphDatabase;
public TransactionWrappingRestfulGraphDatabase( AbstractGraphDatabase graph,
RestfulGraphDatabase restfulGraphDatabase )
{
super( null, null, null );
this.graph = graph;
this.restfulGraphDatabase = restfulGraphDatabase;
}
@Override
public Response addToNodeIndex( ForceMode force, String indexName, String unique, String uniqueness,
String postBody )
{
Transaction transaction = graph.beginTx();
try
{
Response response = restfulGraphDatabase.addToNodeIndex( force, indexName, unique, uniqueness,
postBody );
if ( response.getStatus() < 300 )
{
transaction.success();
}
return response;
}
finally
{
transaction.finish();
}
}
@Override
public Response createRelationship( ForceMode force, long startNodeId, String body )
{
Transaction transaction = graph.beginTx();
try
{
Response response = restfulGraphDatabase.createRelationship( force, startNodeId, body );
if ( response.getStatus() < 300 )
{
transaction.success();
}
return response;
}
finally
{
transaction.finish();
}
}
@Override
public Response deleteNodeIndex( ForceMode force, String indexName )
{
Transaction transaction = graph.beginTx();
try
{
Response response = restfulGraphDatabase.deleteNodeIndex( force, indexName );
transaction.success();
return response;
}
finally
{
transaction.finish();
}
}
@Override
public Response getNodeRelationships( long nodeId, DatabaseActions.RelationshipDirection direction,
AmpersandSeparatedCollection types )
{
Transaction transaction = graph.beginTx();
try
{
Response response = restfulGraphDatabase.getNodeRelationships( nodeId, direction, types );
return response;
}
finally
{
transaction.finish();
}
}
@Override
public Response deleteAllNodeProperties( ForceMode force, long nodeId )
{
Transaction transaction = graph.beginTx();
try
{
Response response = restfulGraphDatabase.deleteAllNodeProperties( force, nodeId );
transaction.success();
return response;
}
finally
{
transaction.finish();
}
}
@Override
public Response getAllNodeProperties( long nodeId )
{
Transaction transaction = graph.beginTx();
try
{
Response response = restfulGraphDatabase.getAllNodeProperties( nodeId );
return response;
}
finally
{
transaction.finish();
}
}
@Override
public Response traverse( long startNode, TraverserReturnType returnType, String body )
{
Transaction transaction = graph.beginTx();
try
{
Response response = restfulGraphDatabase.traverse( startNode, returnType, body );
return response;
}
finally
{
transaction.finish();
}
}
@Override
public Response createNode( ForceMode force, String body )
{
Transaction transaction = graph.beginTx();
try
{
Response response = restfulGraphDatabase.createNode( force, body );
if ( response.getStatus() < 300 )
{
transaction.success();
}
return response;
}
finally
{
transaction.finish();
}
}
@Override
public Response deleteAllRelationshipProperties( ForceMode force, long relationshipId )
{
Transaction transaction = graph.beginTx();
try
{
Response response = restfulGraphDatabase.deleteAllRelationshipProperties( force, relationshipId );
transaction.success();
return response;
}
finally
{
transaction.finish();
}
}
@Override
public Response addToRelationshipIndex( ForceMode force, String indexName, String unique, String uniqueness,
String postBody )
{
Transaction transaction = graph.beginTx();
try
{
Response response = restfulGraphDatabase.addToRelationshipIndex( force, indexName, unique, uniqueness,
postBody );
if ( response.getStatus() < 300 )
{
transaction.success();
}
return response;
}
finally
{
transaction.finish();
}
}
@Override
public Response getIndexedNodes( String indexName, String key, String value )
{
Transaction transaction = graph.beginTx();
try
{
Response response = restfulGraphDatabase.getIndexedNodes( indexName, key, value );
return response;
}
finally
{
transaction.finish();
}
}
@Override
public Response getRelationshipIndexRoot()
{
Transaction transaction = graph.beginTx();
try
{
Response response = restfulGraphDatabase.getRelationshipIndexRoot();
return response;
}
finally
{
transaction.finish();
}
}
@Override
public Response setRelationshipProperty( ForceMode force, long relationshipId, String key, String body )
{
Transaction transaction = graph.beginTx();
try
{
Response response = restfulGraphDatabase.setRelationshipProperty( force, relationshipId, key, body );
transaction.success();
return response;
}
finally
{
transaction.finish();
}
}
@Override
public Response getSchemaConstraintsForLabelAndPropertyUniqueness( String labelName,
AmpersandSeparatedCollection propertyKeys )
{
throw new UnsupportedOperationException( "TODO" );
}
@Override
public Response getSchemaConstraintsForLabelAndUniqueness( String labelName )
{
throw new UnsupportedOperationException( "TODO" );
}
@Override
public Response getSchemaConstraintsForLabel( String labelName )
{
throw new UnsupportedOperationException( "TODO" );
}
@Override
public Response getSchemaConstraints()
{
throw new UnsupportedOperationException( "TODO" );
}
@Override
public Response dropPropertyUniquenessConstraint( String labelName,
AmpersandSeparatedCollection properties )
{
throw new UnsupportedOperationException( "TODO" );
}
@Override
public Response createPropertyUniquenessConstraint( String labelName, String body )
{
try ( Transaction transaction = graph.beginTx() )
{
Response response = restfulGraphDatabase.createPropertyUniquenessConstraint( labelName, body );
if ( response.getStatus() < 300 )
{
transaction.success();
}
return response;
}
}
@Override
public Response getSchemaIndexesForLabel( String labelName )
{
throw new UnsupportedOperationException( "TODO" );
}
@Override
public Response dropSchemaIndex( String labelName,
AmpersandSeparatedCollection properties )
{
throw new UnsupportedOperationException( "TODO" );
}
@Override
public Response createSchemaIndex( String labelName, String body )
{
throw new UnsupportedOperationException( "TODO" );
}
@Override
public Response allPaths( long startNode, String body )
{
Transaction transaction = graph.beginTx();
try
{
return restfulGraphDatabase.allPaths( startNode, body );
}
finally
{
transaction.finish();
}
}
@Override
public Response singlePath( long startNode, String body )
{
Transaction transaction = graph.beginTx();
try
{
return restfulGraphDatabase.singlePath( startNode, body );
}
finally
{
transaction.finish();
}
}
@Override
public Response createPagedTraverser( long startNode, TraverserReturnType returnType, int pageSize,
int leaseTimeInSeconds, String body )
{
Transaction transaction = graph.beginTx();
try
{
Response response = restfulGraphDatabase.createPagedTraverser( startNode, returnType, pageSize,
leaseTimeInSeconds, body );
transaction.success();
return response;
}
finally
{
transaction.finish();
}
}
@Override
public Response pagedTraverse( String traverserId,
TraverserReturnType returnType )
{
Transaction transaction = graph.beginTx();
try
{
return restfulGraphDatabase.pagedTraverse( traverserId, returnType );
}
finally
{
transaction.finish();
}
}
@Override
public Response removePagedTraverser( String traverserId )
{
Transaction transaction = graph.beginTx();
try
{
Response response = restfulGraphDatabase.removePagedTraverser( traverserId );
transaction.success();
return response;
}
finally
{
transaction.finish();
}
}
@Override
public Response deleteFromRelationshipIndex( ForceMode force,
String indexName, long id )
{
throw new UnsupportedOperationException( "TODO" );
}
@Override
public Response deleteFromRelationshipIndexNoValue( ForceMode force, String indexName, String key, long id )
{
throw new UnsupportedOperationException( "TODO" );
}
@Override
public Response deleteFromRelationshipIndex( ForceMode force,
String indexName, String key, String value, long id )
{
Transaction transaction = graph.beginTx();
try
{
Response response = restfulGraphDatabase.deleteFromRelationshipIndex( force, indexName, key, value, id );
if ( response.getStatus() < 300 )
{
transaction.success();
}
return response;
}
finally
{
transaction.finish();
}
}
@Override
public Response deleteFromNodeIndexNoKeyValue( ForceMode force, String indexName, long id )
{
throw new UnsupportedOperationException( "TODO" );
}
@Override
public Response deleteFromNodeIndexNoValue( ForceMode force, String indexName, String key, long id )
{
throw new UnsupportedOperationException( "TODO" );
}
@Override
public Response deleteFromNodeIndex( ForceMode force,
String indexName, String key, String value, long id )
{
Transaction transaction = graph.beginTx();
try
{
Response response = restfulGraphDatabase.deleteFromNodeIndex( force, indexName, key, value, id );
if ( response.getStatus() < 300 )
{
transaction.success();
}
return response;
}
finally
{
transaction.finish();
}
}
@Override
public Response getIndexedRelationshipsByQuery( String indexName,
String key, String query, String order )
{
Transaction transaction = graph.beginTx();
try
{
return restfulGraphDatabase.getIndexedRelationshipsByQuery( indexName, key, query, order );
}
finally
{
transaction.finish();
}
}
@Override
public Response getIndexedRelationshipsByQuery( String indexName,
String query, String order )
{
Transaction transaction = graph.beginTx();
try
{
return restfulGraphDatabase.getIndexedRelationshipsByQuery( indexName, query, order );
}
finally
{
transaction.finish();
}
}
@Override
public Response stopAutoIndexingProperty( String type, String property )
{
Transaction transaction = graph.beginTx();
try
{
Response response = restfulGraphDatabase.stopAutoIndexingProperty( type, property );
transaction.success();
return response;
}
finally
{
transaction.finish();
}
}
@Override
public Response startAutoIndexingProperty( String type, String property )
{
Transaction transaction = graph.beginTx();
try
{
Response response = restfulGraphDatabase.startAutoIndexingProperty( type, property );
transaction.success();
return response;
}
finally
{
transaction.finish();
}
}
@Override
public Response getAutoIndexedProperties( String type )
{
Transaction transaction = graph.beginTx();
try
{
return restfulGraphDatabase.getAutoIndexedProperties( type );
}
finally
{
transaction.finish();
}
}
@Override
public Response setAutoIndexerEnabled( String type, String enable )
{
Transaction transaction = graph.beginTx();
try
{
Response response = restfulGraphDatabase.setAutoIndexerEnabled( type, enable );
transaction.success();
return response;
}
finally
{
transaction.finish();
}
}
@Override
public Response isAutoIndexerEnabled( String type )
{
Transaction transaction = graph.beginTx();
try
{
return restfulGraphDatabase.isAutoIndexerEnabled( type );
}
finally
{
transaction.finish();
}
}
@Override
public Response getIndexedRelationships( String indexName, String key,
String value )
{
Transaction transaction = graph.beginTx();
try
{
return restfulGraphDatabase.getIndexedRelationships( indexName, key, value );
}
finally
{
transaction.finish();
}
}
@Override
public Response getIndexedNodesByQuery( String indexName, String key,
String query, String order )
{
Transaction transaction = graph.beginTx();
try
{
return restfulGraphDatabase.getIndexedNodesByQuery( indexName, key, query, order );
}
finally
{
transaction.finish();
}
}
@Override
public Response getAutoIndexedNodes( String type, String key, String value )
{
throw new UnsupportedOperationException( "TODO" );
}
@Override
public Response getRelationshipFromIndexUri( String indexName, String key, String value, long id )
{
Transaction transaction = graph.beginTx();
try
{
return restfulGraphDatabase.getRelationshipFromIndexUri( indexName, key, value, id );
}
finally
{
transaction.finish();
}
}
@Override
public Response getNodeFromIndexUri( String indexName, String key, String value, long id )
{
Transaction transaction = graph.beginTx();
try
{
return restfulGraphDatabase.getNodeFromIndexUri( indexName, key, value, id );
}
finally
{
transaction.finish();
}
}
@Override
public Response deleteRelationshipIndex( ForceMode force, String indexName )
{
Transaction transaction = graph.beginTx();
try
{
Response response = restfulGraphDatabase.deleteRelationshipIndex( force, indexName );
transaction.success();
return response;
}
finally
{
transaction.finish();
}
}
@Override
public Response getAutoIndexedNodesByQuery( String type, String query )
{
throw new UnsupportedOperationException( "TODO" );
}
@Override
public Response getIndexedNodesByQuery( String indexName, String
query, String order )
{
Transaction transaction = graph.beginTx();
try
{
return restfulGraphDatabase.getIndexedNodesByQuery( indexName, query, order );
}
finally
{
transaction.finish();
}
}
@Override
public Response jsonCreateRelationshipIndex( ForceMode force, String json )
{
Transaction transaction = graph.beginTx();
try
{
Response response = restfulGraphDatabase.jsonCreateRelationshipIndex( force, json );
transaction.success();
return response;
}
finally
{
transaction.finish();
}
}
@Override
public Response jsonCreateNodeIndex( ForceMode force, String json )
{
Transaction transaction = graph.beginTx();
try
{
Response response = restfulGraphDatabase.jsonCreateNodeIndex( force, json );
transaction.success();
return response;
}
finally
{
transaction.finish();
}
}
@Override
public Response getNodeIndexRoot()
{
Transaction transaction = graph.beginTx();
try
{
return restfulGraphDatabase.getNodeIndexRoot();
}
finally
{
transaction.finish();
}
}
@Override
public Response deleteRelationshipProperty( ForceMode force, long relationshipId, String key )
{
Transaction transaction = graph.beginTx();
try
{
Response response = restfulGraphDatabase.deleteRelationshipProperty( force, relationshipId, key );
if ( response.getStatus() < 300 )
{
transaction.success();
}
return response;
}
finally
{
transaction.finish();
}
}
@Override
public Response setAllRelationshipProperties( ForceMode force,
long relationshipId, String body )
{
Transaction transaction = graph.beginTx();
try
{
Response response = restfulGraphDatabase.setAllRelationshipProperties( force, relationshipId, body );
transaction.success();
return response;
}
finally
{
transaction.finish();
}
}
@Override
public Response getRelationshipProperty( long relationshipId,
String key )
{
Transaction transaction = graph.beginTx();
try
{
return restfulGraphDatabase.getRelationshipProperty( relationshipId, key );
}
finally
{
transaction.finish();
}
}
@Override
public Response getAllRelationshipProperties( long relationshipId )
{
Transaction transaction = graph.beginTx();
try
{
return restfulGraphDatabase.getAllRelationshipProperties( relationshipId );
}
finally
{
transaction.finish();
}
}
@Override
public Response getNodeRelationships( long nodeId, DatabaseActions.RelationshipDirection direction )
{
throw new UnsupportedOperationException( "TODO" );
}
@Override
public Response deleteRelationship( ForceMode force, long relationshipId )
{
Transaction transaction = graph.beginTx();
try
{
Response response = restfulGraphDatabase.deleteRelationship( force, relationshipId );
transaction.success();
return response;
}
finally
{
transaction.finish();
}
}
@Override
public Response getRelationship( long relationshipId )
{
Transaction transaction = graph.beginTx();
try
{
return restfulGraphDatabase.getRelationship( relationshipId );
}
finally
{
transaction.finish();
}
}
@Override
public Response getAllLabels()
{
throw new UnsupportedOperationException( "TODO" );
}
@Override
public Response getNodesWithLabelAndProperty( String labelName, UriInfo uriInfo )
{
throw new UnsupportedOperationException( "TODO" );
}
@Override
public Response getNodeLabels( ForceMode force, long nodeId )
{
try ( Transaction ignored = graph.beginTx() )
{
return restfulGraphDatabase.getNodeLabels( force, nodeId );
}
}
@Override
public Response removeNodeLabel( ForceMode force, long
nodeId, String labelName )
{
throw new UnsupportedOperationException( "TODO" );
}
@Override
public Response setNodeLabels( ForceMode force, long nodeId, String body )
{
throw new UnsupportedOperationException( "TODO" );
}
@Override
public Response addNodeLabel( ForceMode force, long nodeId, String body )
{
try ( Transaction transaction = graph.beginTx() )
{
Response response = restfulGraphDatabase.addNodeLabel( force, nodeId, body );
if ( response.getStatus() < 300 )
{
transaction.success();
}
return response;
}
}
@Override
public Response deleteNodeProperty( ForceMode force, long nodeId, String key )
{
Transaction transaction = graph.beginTx();
try
{
Response response = restfulGraphDatabase.deleteNodeProperty( force, nodeId, key );
if ( response.getStatus() < 300 )
{
transaction.success();
}
return response;
}
finally
{
transaction.finish();
}
}
@Override
public Response getNodeProperty( ForceMode force, long
nodeId, String key )
{
Transaction transaction = graph.beginTx();
try
{
return restfulGraphDatabase.getNodeProperty( force, nodeId, key );
}
finally
{
transaction.finish();
}
}
@Override
public Response setNodeProperty( ForceMode force, long
nodeId, String key, String body )
{
try (Transaction transaction = graph.beginTx())
{
Response response = restfulGraphDatabase.setNodeProperty( force, nodeId, key, body );
if (response.getStatus() < 300)
{
transaction.success();
}
return response;
}
}
@Override
public Response setAllNodeProperties( ForceMode force, long nodeId, String body )
{
Transaction transaction = graph.beginTx();
try
{
Response response = restfulGraphDatabase.setAllNodeProperties( force, nodeId, body );
if ( response.getStatus() < 300 )
{
transaction.success();
}
return response;
}
finally
{
transaction.finish();
}
}
@Override
public Response deleteNode( ForceMode force, long nodeId )
{
Transaction transaction = graph.beginTx();
try
{
Response response = restfulGraphDatabase.deleteNode( force, nodeId );
if ( response.getStatus() < 300 )
{
transaction.success();
}
return response;
}
finally
{
transaction.finish();
}
}
@Override
public Response getNode( long nodeId )
{
Transaction transaction = graph.beginTx();
try
{
return restfulGraphDatabase.getNode( nodeId );
}
finally
{
transaction.finish();
}
}
@Override
public Response getRoot()
{
Transaction transaction = graph.beginTx();
try
{
return restfulGraphDatabase.getRoot();
}
finally
{
transaction.finish();
}
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_web_TransactionWrappingRestfulGraphDatabase.java
|
1,752
|
public class TransactionWrappedDatabaseActions extends DatabaseActions
{
private final GraphDatabaseAPI graph;
public TransactionWrappedDatabaseActions( LeaseManager leaseManager, ForceMode forced, GraphDatabaseAPI graph )
{
super( leaseManager, forced, graph );
this.graph = graph;
}
@Override
public NodeRepresentation createNode( Map<String, Object> properties, Label... labels ) throws
PropertyValueException
{
Transaction transaction = graph.beginTx();
try
{
NodeRepresentation nodeRepresentation = super.createNode( properties, labels );
transaction.success();
return nodeRepresentation;
}
finally
{
transaction.finish();
}
}
@Override
public NodeRepresentation getNode( long nodeId ) throws NodeNotFoundException
{
Transaction transaction = graph.beginTx();
try
{
NodeRepresentation node = super.getNode( nodeId );
transaction.success();
return node;
}
finally
{
transaction.finish();
}
}
@Override
public void deleteNode( long nodeId ) throws NodeNotFoundException, OperationFailureException
{
Transaction transaction = graph.beginTx();
try
{
super.deleteNode( nodeId );
transaction.success();
}
finally
{
transaction.finish();
}
}
@Override
public void setNodeProperty( long nodeId, String key, Object value ) throws PropertyValueException,
NodeNotFoundException
{
Transaction transaction = graph.beginTx();
try
{
super.setNodeProperty( nodeId, key, value );
transaction.success();
}
finally
{
transaction.finish();
}
}
@Override
public void removeNodeProperty( long nodeId, String key ) throws NodeNotFoundException, NoSuchPropertyException
{
Transaction transaction = graph.beginTx();
try
{
super.removeNodeProperty( nodeId, key );
transaction.success();
}
finally
{
transaction.finish();
}
}
@Override
public void setAllNodeProperties( long nodeId, Map<String, Object> properties ) throws PropertyValueException,
NodeNotFoundException
{
Transaction transaction = graph.beginTx();
try
{
super.setAllNodeProperties( nodeId, properties );
transaction.success();
}
finally
{
transaction.finish();
}
}
@Override
public void removeAllNodeProperties( long nodeId ) throws NodeNotFoundException, PropertyValueException
{
Transaction transaction = graph.beginTx();
try
{
super.removeAllNodeProperties( nodeId );
transaction.success();
}
finally
{
transaction.finish();
}
}
@Override
public void addLabelToNode( long nodeId, Collection<String> labelNames ) throws NodeNotFoundException,
BadInputException
{
Transaction transaction = graph.beginTx();
try
{
super.addLabelToNode( nodeId, labelNames );
transaction.success();
}
finally
{
transaction.finish();
}
}
@Override
public void removeLabelFromNode( long nodeId, String labelName ) throws NodeNotFoundException
{
Transaction transaction = graph.beginTx();
try
{
super.removeLabelFromNode( nodeId, labelName );
transaction.success();
}
finally
{
transaction.finish();
}
}
@Override
public IndexRepresentation createNodeIndex( Map<String, Object> indexSpecification )
{
Transaction transaction = graph.beginTx();
try
{
IndexRepresentation indexRepresentation = super.createNodeIndex( indexSpecification );
transaction.success();
return indexRepresentation;
}
finally
{
transaction.finish();
}
}
@Override
public RelationshipRepresentation createRelationship( long startNodeId, long endNodeId, String type, Map<String,
Object> properties ) throws StartNodeNotFoundException, EndNodeNotFoundException, PropertyValueException
{
Transaction transaction = graph.beginTx();
try
{
RelationshipRepresentation relationshipRepresentation = super.createRelationship( startNodeId, endNodeId,
type,
properties );
transaction.success();
return relationshipRepresentation;
}
finally
{
transaction.finish();
}
}
@Override
public RelationshipRepresentation getRelationship( long relationshipId ) throws RelationshipNotFoundException
{
Transaction transaction = graph.beginTx();
try
{
RelationshipRepresentation relationship = super.getRelationship( relationshipId );
transaction.success();
return relationship;
}
finally
{
transaction.finish();
}
}
@Override
public void deleteRelationship( long relationshipId ) throws RelationshipNotFoundException
{
Transaction transaction = graph.beginTx();
try
{
super.deleteRelationship( relationshipId );
transaction.success();
}
finally
{
transaction.finish();
}
}
@Override
public ListRepresentation getNodeRelationships( long nodeId, RelationshipDirection direction, Collection<String>
types ) throws NodeNotFoundException
{
Transaction transaction = graph.beginTx();
try
{
ListRepresentation nodeRelationships = super.getNodeRelationships( nodeId, direction, types );
transaction.success();
return nodeRelationships;
}
finally
{
transaction.finish();
}
}
@Override
public void setAllRelationshipProperties( long relationshipId, Map<String, Object> properties ) throws
PropertyValueException, RelationshipNotFoundException
{
Transaction transaction = graph.beginTx();
try
{
super.setAllRelationshipProperties( relationshipId, properties );
transaction.success();
}
finally
{
transaction.finish();
}
}
@Override
public void setRelationshipProperty( long relationshipId, String key, Object value ) throws
PropertyValueException, RelationshipNotFoundException
{
Transaction transaction = graph.beginTx();
try
{
super.setRelationshipProperty( relationshipId, key, value );
transaction.success();
}
finally
{
transaction.finish();
}
}
@Override
public void removeAllRelationshipProperties( long relationshipId ) throws RelationshipNotFoundException,
PropertyValueException
{
Transaction transaction = graph.beginTx();
try
{
super.removeAllRelationshipProperties( relationshipId );
transaction.success();
}
finally
{
transaction.finish();
}
}
@Override
public void removeRelationshipProperty( long relationshipId, String key ) throws RelationshipNotFoundException,
NoSuchPropertyException
{
Transaction transaction = graph.beginTx();
try
{
super.removeRelationshipProperty( relationshipId, key );
transaction.success();
}
finally
{
transaction.finish();
}
}
@Override
public IndexedEntityRepresentation addToNodeIndex( String indexName, String key, String value, long nodeId )
{
Transaction transaction = graph.beginTx();
try
{
IndexedEntityRepresentation indexedEntityRepresentation = super.addToNodeIndex( indexName, key, value,
nodeId );
transaction.success();
return indexedEntityRepresentation;
}
finally
{
transaction.finish();
}
}
@Override
public void removeFromNodeIndex( String indexName, String key, String value, long id )
{
Transaction transaction = graph.beginTx();
try
{
super.removeFromNodeIndex( indexName, key, value, id );
transaction.success();
}
finally
{
transaction.finish();
}
}
@Override
public void removeFromNodeIndexNoValue( String indexName, String key, long id )
{
Transaction transaction = graph.beginTx();
try
{
super.removeFromNodeIndexNoValue( indexName, key, id );
transaction.success();
}
finally
{
transaction.finish();
}
}
@Override
public void removeFromNodeIndexNoKeyValue( String indexName, long id )
{
Transaction transaction = graph.beginTx();
try
{
super.removeFromNodeIndexNoKeyValue( indexName, id );
transaction.success();
}
finally
{
transaction.finish();
}
}
@Override
public PathRepresentation findSinglePath( long startId, long endId, Map<String, Object> map )
{
Transaction transaction = graph.beginTx();
try
{
PathRepresentation singlePath = super.findSinglePath( startId, endId, map );
transaction.success();
return singlePath;
}
finally
{
transaction.finish();
}
}
@Override
public ListRepresentation getNodesWithLabel( String labelName, Map<String, Object> properties )
{
Transaction transaction = graph.beginTx();
try
{
ListRepresentation nodesWithLabel = super.getNodesWithLabel( labelName, properties );
transaction.success();
return nodesWithLabel;
}
finally
{
transaction.finish();
}
}
@Override
public IndexDefinitionRepresentation createSchemaIndex( String labelName, Iterable<String> propertyKey )
{
Transaction transaction = graph.beginTx();
try
{
IndexDefinitionRepresentation indexDefinitionRepresentation = super.createSchemaIndex( labelName,
propertyKey );
transaction.success();
return indexDefinitionRepresentation;
}
finally
{
transaction.finish();
}
}
@Override
public boolean dropSchemaIndex( String labelName, String propertyKey )
{
Transaction transaction = graph.beginTx();
try
{
boolean result = super.dropSchemaIndex( labelName, propertyKey );
transaction.success();
return result;
}
finally
{
transaction.finish();
}
}
@Override
public ConstraintDefinitionRepresentation createPropertyUniquenessConstraint( String labelName,
Iterable<String> propertyKeys )
{
Transaction transaction = graph.beginTx();
try
{
ConstraintDefinitionRepresentation constraintDefinitionRepresentation = super
.createPropertyUniquenessConstraint( labelName, propertyKeys );
transaction.success();
return constraintDefinitionRepresentation;
}
finally
{
transaction.finish();
}
}
@Override
public boolean dropPropertyUniquenessConstraint( String labelName, Iterable<String> propertyKeys )
{
Transaction transaction = graph.beginTx();
try
{
boolean result = super.dropPropertyUniquenessConstraint( labelName, propertyKeys );
transaction.success();
return result;
}
finally
{
transaction.finish();
}
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rest_web_TransactionWrappedDatabaseActions.java
|
1,753
|
public class RrdFactoryTest
{
private Configuration config;
private Database db;
TargetDirectory target = TargetDirectory.forTest( RrdFactoryTest.class );
@Rule
public TargetDirectory.TestDirectory testDirectory = target.testDirectory();
@Rule
public Mute mute = muteAll();
@Before
public void setUp() throws IOException
{
config = new MapConfiguration( new HashMap<String, String>() );
db = new WrappedDatabase( new ImpermanentGraphDatabase(
TargetDirectory.forTest( getClass() ).cleanDirectory( "rrd" ).getAbsolutePath()) );
}
@After
public void tearDown()
{
db.getGraph().shutdown();
}
@Test
public void shouldTakeDirectoryLocationFromConfig() throws Exception
{
String expected = testDirectory.directory().getAbsolutePath();
config.addProperty( Configurator.RRDB_LOCATION_PROPERTY_KEY, expected );
TestableRrdFactory factory = createRrdFactory();
factory.createRrdDbAndSampler( db, new NullJobScheduler() );
assertThat( factory.directoryUsed, is( expected ) );
}
@Test
public void recreateDatabaseIfWrongStepsize() throws Exception
{
String expected = testDirectory.directory().getAbsolutePath();
config.addProperty( Configurator.RRDB_LOCATION_PROPERTY_KEY, expected );
TestableRrdFactory factory = createRrdFactory();
factory.createRrdDbAndSampler( db, new NullJobScheduler() );
assertThat( factory.directoryUsed, is( expected ) );
}
@Test
public void shouldMoveAwayInvalidRrdFile() throws IOException
{
//Given
String expected = new File( testDirectory.directory(), "rrd-test").getAbsolutePath();
config.addProperty( Configurator.RRDB_LOCATION_PROPERTY_KEY, expected );
TestableRrdFactory factory = createRrdFactory();
createInvalidRrdFile( expected );
//When
RrdDbWrapper rrdDbAndSampler = factory.createRrdDbAndSampler( db, new NullJobScheduler() );
//Then
assertSubdirectoryExists( "rrd-test-invalid", factory.directoryUsed );
rrdDbAndSampler.close();
}
private void createInvalidRrdFile( String expected ) throws IOException
{
// create invalid rrd
File rrd = new File( expected );
RrdDef rrdDef = new RrdDef( rrd.getAbsolutePath(), 3000 );
rrdDef.addDatasource( "test", DsType.GAUGE, 1, NaN, NaN );
rrdDef.addArchive( ConsolFun.AVERAGE, 0.2, 1, 1600 );
RrdDb r = new RrdDb( rrdDef );
r.close();
}
@Test
public void shouldCreateRrdFileInTempLocationForImpermanentDatabases() throws IOException
{
// Given
String expected = testDirectory.directory().getAbsolutePath();
TestableRrdFactory factory = createRrdFactory( expected );
// When
factory.createRrdDbAndSampler( db, new NullJobScheduler() );
// Then
assertThat( factory.directoryUsed, is( expected ) );
}
@Test
public void shouldCreateRrdFileInDbSubdirectory() throws Exception
{
String storeDir = testDirectory.directory().getAbsolutePath();
db = new WrappedDatabase( (AbstractGraphDatabase)
new GraphDatabaseFactory().newEmbeddedDatabase( storeDir ) );
TestableRrdFactory factory = createRrdFactory();
// When
factory.createRrdDbAndSampler( db, new NullJobScheduler() );
//Then
String rrdParent = new File( factory.directoryUsed ).getParent();
assertThat( rrdParent, is( storeDir ) );
}
private void assertSubdirectoryExists( final String directoryThatShouldExist, String directoryUsed )
{
File parentFile = new File( directoryUsed ).getParentFile();
String[] list = parentFile.list();
for ( String aList : list )
{
if (aList.startsWith( directoryThatShouldExist ))
{
return;
}
}
fail( String.format( "Didn't find [%s] in [%s]", directoryThatShouldExist, directoryUsed ) );
}
private TestableRrdFactory createRrdFactory()
{
return new TestableRrdFactory( config, new File( testDirectory.directory(), "rrd" ).getAbsolutePath() );
}
private TestableRrdFactory createRrdFactory( String tempRrdFile )
{
return new TestableRrdFactory( config, tempRrdFile );
}
private static class TestableRrdFactory extends RrdFactory
{
public String directoryUsed;
private final String tempRrdFile;
public TestableRrdFactory( Configuration config, String tempRrdFile )
{
super( config, DevNullLoggingService.DEV_NULL );
this.tempRrdFile = tempRrdFile;
}
@Override
protected String tempRrdFile() throws IOException
{
return tempRrdFile;
}
@Override
protected RrdDbWrapper createRrdb( String inDirectory, boolean ephemeral, Sampleable... sampleables )
{
directoryUsed = inDirectory;
return super.createRrdb( inDirectory, ephemeral, sampleables );
}
}
private static class NullJobScheduler implements JobScheduler
{
@Override
public void scheduleAtFixedRate( Runnable job, String name, long delay, long period )
{
}
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rrd_RrdFactoryTest.java
|
1,754
|
private static class TestableRrdFactory extends RrdFactory
{
public String directoryUsed;
private final String tempRrdFile;
public TestableRrdFactory( Configuration config, String tempRrdFile )
{
super( config, DevNullLoggingService.DEV_NULL );
this.tempRrdFile = tempRrdFile;
}
@Override
protected String tempRrdFile() throws IOException
{
return tempRrdFile;
}
@Override
protected RrdDbWrapper createRrdb( String inDirectory, boolean ephemeral, Sampleable... sampleables )
{
directoryUsed = inDirectory;
return super.createRrdb( inDirectory, ephemeral, sampleables );
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rrd_RrdFactoryTest.java
|
1,755
|
public class GlobalJavascriptInitializer
{
private static Mode initializationMode;
public static enum Mode
{
SANDBOXED,
UNSAFE
}
public static synchronized void initialize(Mode requestedMode)
{
if(initializationMode != null)
{
if(initializationMode == requestedMode)
{
return;
}
else
{
throw new RuntimeException( "Cannot initialize javascript context twice, " +
"system is currently initialized as: '" + initializationMode.name() + "'." );
}
}
initializationMode = requestedMode;
ContextFactory contextFactory;
switch(requestedMode)
{
case UNSAFE:
contextFactory = new ContextFactory()
{
protected Context makeContext()
{
Context cx = super.makeContext();
cx.setLanguageVersion( Context.VERSION_1_7 );
// TODO: This goes up to 9, do performance tests to determine appropriate level of optimization
cx.setOptimizationLevel( 4 );
return cx;
}
};
break;
default:
contextFactory = new ContextFactory()
{
protected Context makeContext()
{
Context cx = super.makeContext();
ClassShutter shutter = new WhiteListClassShutter( UserScriptClassWhiteList.getWhiteList() );
cx.setLanguageVersion( Context.VERSION_1_7 );
// TODO: This goes up to 9, do performance tests to determine appropriate level of optimization
cx.setOptimizationLevel( 4 );
cx.setClassShutter( shutter );
cx.setWrapFactory( new WhiteListJavaWrapper( shutter ) );
return cx;
}
};
break;
}
ContextFactory.initGlobal( contextFactory );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_scripting_javascript_GlobalJavascriptInitializer.java
|
1,756
|
public class RrdJob implements Runnable {
private static final long MIN_STEP_TIME = 1;
private RrdSampler[] sampler;
private long lastRun = 0;
private TimeSource timeSource;
public RrdJob(RrdSampler... sampler) {
this(new SystemBackedTimeSource(), sampler);
}
public RrdJob(TimeSource timeSource, RrdSampler... sampler) {
this.sampler = sampler;
this.timeSource = timeSource;
}
public void run() {
// Guard against getting run in too rapid succession.
if ((timeSource.getTime() - lastRun) >= MIN_STEP_TIME) {
lastRun = timeSource.getTime();
for (RrdSampler rrdSampler : sampler) {
rrdSampler.updateSample();
}
}
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rrd_RrdJob.java
|
1,757
|
public class UserScriptClassWhiteList
{
public static Set<String> getWhiteList()
{
HashSet<String> safe = new HashSet<String>();
// Core API concepts
safe.add( Path.class.getName() );
safe.add( Node.class.getName() );
safe.add( Relationship.class.getName() );
safe.add( RelationshipType.class.getName() );
safe.add( DynamicRelationshipType.class.getName() );
safe.add( Lock.class.getName() );
safe.add( NotFoundException.class.getName() );
// Traversal concepts
safe.add( Direction.class.getName() );
safe.add( Evaluation.class.getName() );
// Java Core API
safe.add( Object.class.getName() );
safe.add( String.class.getName() );
safe.add( Integer.class.getName() );
safe.add( Long.class.getName() );
safe.add( Float.class.getName() );
safe.add( Double.class.getName() );
safe.add( Boolean.class.getName() );
// This is a work-around, since these are not supposed to be publicly available.
// The reason we need to add it here is, most likely, that some methods in the API
// returns these rather than the corresponding interfaces, which means our white list
// checker doesn't know which interface to cast to (since there could be several). Instead
// we allow users direct access to these classes for now.
safe.add( "org.neo4j.kernel.impl.traversal.StartNodeTraversalBranch" );
safe.add( "org.neo4j.kernel.impl.traversal.TraversalBranchImpl" );
safe.add( "org.neo4j.kernel.impl.core.NodeProxy" );
return safe;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_scripting_UserScriptClassWhiteList.java
|
1,758
|
public class TestScriptExecutorFactoryRepository
{
@Test(expected = NoSuchScriptLanguageException.class)
public void shouldThrowNoSuchScriptLanguageExceptionForUnkownLanguages() throws Exception
{
// Given
ScriptExecutorFactoryRepository repo = new ScriptExecutorFactoryRepository( new HashMap<String, ScriptExecutor.Factory>() );
// When
repo.getFactory( "Blah" );
}
@Test
public void shouldReturnRegisteredFactory() throws Exception
{
// Given
Map<String, ScriptExecutor.Factory> languages = new HashMap<String, ScriptExecutor.Factory>( );
languages.put( "js", mock(ScriptExecutor.Factory.class) );
ScriptExecutorFactoryRepository repo = new ScriptExecutorFactoryRepository( languages );
// When
ScriptExecutor.Factory factory = repo.getFactory( "js" );
// Then
assertThat(factory, not(nullValue()));
}
}
| false
|
community_server_src_test_java_org_neo4j_server_scripting_TestScriptExecutorFactoryRepository.java
|
1,759
|
public class ScriptExecutorFactoryRepository
{
private final Map<String, ScriptExecutor.Factory> languages;
public ScriptExecutorFactoryRepository( Map<String, ScriptExecutor.Factory> languages )
{
this.languages = Collections.unmodifiableMap( languages );
}
public ScriptExecutor.Factory getFactory( String language )
{
if(languages.containsKey( language ))
{
return languages.get( language );
} else
{
throw new NoSuchScriptLanguageException( "Unknown scripting language '" + language + "'." );
}
}
}
| false
|
community_server_src_main_java_org_neo4j_server_scripting_ScriptExecutorFactoryRepository.java
|
1,760
|
public class NoSuchScriptLanguageException extends RuntimeException
{
public NoSuchScriptLanguageException( String msg )
{
super(msg);
}
}
| false
|
community_server_src_main_java_org_neo4j_server_scripting_NoSuchScriptLanguageException.java
|
1,761
|
public class GroovyScriptExecutor implements ScriptExecutor
{
@Override
public Object execute( Map<String, Object> variables ) throws EvaluationException
{
return null;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_scripting_GroovyScriptExecutor.java
|
1,762
|
public class RelationshipCountSampleable extends DatabasePrimitivesSampleableBase
{
public RelationshipCountSampleable( NodeManager nodeManager )
{
super( nodeManager );
}
@Override public String getName()
{
return "relationship_count";
}
@Override public double getValue()
{
return getNodeManager().getNumberOfIdsInUse( Relationship.class );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rrd_sampler_RelationshipCountSampleable.java
|
1,763
|
public class PropertyCountSampleable extends DatabasePrimitivesSampleableBase
{
public PropertyCountSampleable( NodeManager nodeManager )
{
super( nodeManager );
}
@Override public String getName()
{
return "property_count";
}
@Override public double getValue()
{
return getNodeManager().getNumberOfIdsInUse( PropertyStore.class );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rrd_sampler_PropertyCountSampleable.java
|
1,764
|
public class NodeIdsInUseSampleable extends DatabasePrimitivesSampleableBase
{
public NodeIdsInUseSampleable( NodeManager nodeManager )
{
super( nodeManager );
}
@Override public String getName()
{
return "node_count";
}
@Override public double getValue()
{
return getNodeManager().getNumberOfIdsInUse( Node.class );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rrd_sampler_NodeIdsInUseSampleable.java
|
1,765
|
public class MemoryUsedSampleable implements Sampleable
{
private final ObjectName memoryName;
public MemoryUsedSampleable()
{
try
{
memoryName = new ObjectName( "java.lang:type=Memory" );
} catch ( MalformedObjectNameException e )
{
throw new RuntimeException( e );
}
}
@Override
public String getName()
{
return "memory_usage_percent";
}
@Override
public double getValue()
{
CompositeDataSupport heapMemoryUsage = JmxUtils.getAttribute( memoryName, "HeapMemoryUsage" );
long used = (Long) heapMemoryUsage.get( "used" );
long max = (Long) heapMemoryUsage.get( "max" );
return Math.ceil( 100.0 * used / max );
}
@Override
public DsType getType()
{
return DsType.GAUGE;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rrd_sampler_MemoryUsedSampleable.java
|
1,766
|
public abstract class DatabasePrimitivesSampleableBase implements Sampleable
{
private final NodeManager nodeManager;
public DatabasePrimitivesSampleableBase( NodeManager nodeManager )
{
if(nodeManager == null)
{
throw new RuntimeException( "Database sampler needs a node manager to work, was given null." );
}
this.nodeManager = nodeManager;
}
protected NodeManager getNodeManager()
{
return nodeManager;
}
@Override
public DsType getType()
{
return DsType.GAUGE;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rrd_sampler_DatabasePrimitivesSampleableBase.java
|
1,767
|
public class UnableToSampleException extends RuntimeException
{
private static final long serialVersionUID = 112443232112435425L;
}
| false
|
community_server_src_main_java_org_neo4j_server_rrd_UnableToSampleException.java
|
1,768
|
public class SystemBackedTimeSource implements TimeSource
{
@Override
public long getTime()
{
return Util.getTime();
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rrd_SystemBackedTimeSource.java
|
1,769
|
{
@Override
public void run()
{
try
{
job.run();
} catch ( Exception e )
{
logging.getConsoleLog( getClass() ).warn( "Unable to execute scheduled job", e );
}
}
};
| false
|
community_server_src_main_java_org_neo4j_server_rrd_ScheduledJob.java
|
1,770
|
public class ScheduledJob
{
private final Timer timer;
public ScheduledJob( final Runnable job, String name, long delay, long period, final Logging logging )
{
timer = new Timer( name );
TimerTask runJob = new TimerTask()
{
@Override
public void run()
{
try
{
job.run();
} catch ( Exception e )
{
logging.getConsoleLog( getClass() ).warn( "Unable to execute scheduled job", e );
}
}
};
timer.scheduleAtFixedRate( runJob, delay, period );
}
public void cancel()
{
timer.cancel();
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rrd_ScheduledJob.java
|
1,771
|
private class TestSamplable implements Sampleable
{
private String name;
private double value;
private TestSamplable( String name, double value )
{
this.name = name;
this.value = value;
}
public String getName()
{
return name;
}
public double getValue()
{
return value;
}
public DsType getType()
{
return DsType.GAUGE;
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rrd_RrdSamplerTest.java
|
1,772
|
private class FailingSamplable implements Sampleable
{
private String name;
private FailingSamplable( String name )
{
this.name = name;
}
public String getName()
{
return name;
}
public double getValue()
{
throw new UnableToSampleException();
}
public DsType getType()
{
return DsType.GAUGE;
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rrd_RrdSamplerTest.java
|
1,773
|
public class RrdSamplerTest
{
@Test
public void canSampleADatabase() throws IOException
{
Sampleable testSamplable = new TestSamplable( "myTest", 15 );
RrdDb rrd = mock( RrdDb.class );
final Sample sample = mock( Sample.class );
when( rrd.createSample( anyLong() ) ).thenReturn( sample );
RrdSampler sampler = new RrdSamplerImpl( rrd, testSamplable );
sampler.updateSample();
verify( sample ).setValue( "myTest", 15 );
}
@Test
public void shouldIgnoreUnableToSampleExceptions() throws IOException
{
Sampleable failingSampleable = new FailingSamplable( "myTest" );
RrdDb rrd = mock( RrdDb.class );
final Sample sample = mock( Sample.class );
when( rrd.createSample( anyLong() ) ).thenReturn( sample );
RrdSampler sampler = new RrdSamplerImpl( rrd, failingSampleable );
sampler.updateSample();
verify( sample, never() ).setValue( "myTest", 15 );
}
private class TestSamplable implements Sampleable
{
private String name;
private double value;
private TestSamplable( String name, double value )
{
this.name = name;
this.value = value;
}
public String getName()
{
return name;
}
public double getValue()
{
return value;
}
public DsType getType()
{
return DsType.GAUGE;
}
}
private class FailingSamplable implements Sampleable
{
private String name;
private FailingSamplable( String name )
{
this.name = name;
}
public String getName()
{
return name;
}
public double getValue()
{
throw new UnableToSampleException();
}
public DsType getType()
{
return DsType.GAUGE;
}
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rrd_RrdSamplerTest.java
|
1,774
|
public class RrdSamplerImpl implements RrdSampler {
/**
* The current sampling object. This is created when calling #start().
*/
private RrdDb rrdDb;
private Sampleable[] samplables;
/**
* Keep track of whether to run the update task or not.
*/
protected RrdSamplerImpl(RrdDb rrdDb, Sampleable... samplables) {
this.rrdDb = rrdDb;
this.samplables = samplables;
}
/*
* This method is called each time we want a snapshot of the current system
* state. Data sources to work with are defined in {@link
* RrdManager#getRrdDB()}
*/
@Override public void updateSample()
{
try
{
Sample sample = rrdDb.createSample( Util.getTimestamp() );
for ( Sampleable samplable : samplables )
{
sample.setValue( samplable.getName(), samplable.getValue() );
}
sample.update();
}
catch ( UnableToSampleException e )
{
e.printStackTrace();
}
catch ( IOException e )
{
throw new RuntimeException( "IO Error trying to access round robin database path. See nested exception.", e );
}
}
}
| false
|
community_server_src_main_java_org_neo4j_server_rrd_RrdSamplerImpl.java
|
1,775
|
public class RrdJobTest {
@Test
public void testGuardsAgainstQuickRuns() throws Exception {
RrdSampler sampler = mock(RrdSampler.class);
TimeSource time = mock(TimeSource.class);
stub(time.getTime())
.toReturn(10000l).toReturn(10000l) // First call (getTime gets called twice)
.toReturn(10000l) // Second call
.toReturn(12000l); // Third call
RrdJob job = new RrdJob( time, sampler );
job.run();
job.run();
job.run();
verify(sampler, times(2)).updateSample();
}
}
| false
|
community_server_src_test_java_org_neo4j_server_rrd_RrdJobTest.java
|
1,776
|
public class HTTPLoggingDocIT extends ExclusiveServerTestBase
{
@Test
public void givenExplicitlyDisabledServerLoggingConfigurationShouldNotLogAccesses() throws Exception
{
// given
File logDirectory = TargetDirectory.forTest( this.getClass() ).cleanDirectory(
"givenExplicitlyDisabledServerLoggingConfigurationShouldNotLogAccesses-logdir" );
FileUtils.forceMkdir( logDirectory );
final File confDir = TargetDirectory.forTest( this.getClass() ).cleanDirectory(
"givenExplicitlyDisabledServerLoggingConfigurationShouldNotLogAccesses-confdir" );
FileUtils.forceMkdir( confDir );
final File configFile = HTTPLoggingPreparednessRuleTest.createConfigFile(
HTTPLoggingPreparednessRuleTest.createLogbackConfigXml( logDirectory ), confDir );
NeoServer server = CommunityServerBuilder.server().withDefaultDatabaseTuning()
.withProperty( Configurator.HTTP_LOGGING, "false" )
.withProperty( Configurator.HTTP_LOG_CONFIG_LOCATION, configFile.getPath() )
.usingDatabaseDir( TargetDirectory.forTest( this.getClass() ).cleanDirectory(
"givenExplicitlyDisabledServerLoggingConfigurationShouldNotLogAccesses-dbdir"
).getAbsolutePath() )
.build();
try
{
server.start();
FunctionalTestHelper functionalTestHelper = new FunctionalTestHelper( server );
// when
String query = "?implicitlyDisabled" + UUID.randomUUID().toString();
JaxRsResponse response = new RestRequest().get( functionalTestHelper.webAdminUri() + query );
assertEquals( 200, response.getStatus() );
response.close();
// then
assertFalse( occursIn( query, new File( logDirectory, "http.log" ) ) );
}
finally
{
server.stop();
}
}
@Test
@Ignore( "This test has probably never worked, it fails in an assertion but the test contained a "
+ "catch Throwable -- printStackTrace and so hid the failure. When the catch was removed"
+ "the real problem was revealed" )
public void givenExplicitlyEnabledServerLoggingConfigurationShouldLogAccess() throws Exception
{
// given
final File logDirectory = TargetDirectory.forTest( this.getClass() ).cleanDirectory(
"givenExplicitlyEnabledServerLoggingConfigurationShouldLogAccess-logdir" );
FileUtils.forceMkdir( logDirectory );
final File confDir = TargetDirectory.forTest( this.getClass() ).cleanDirectory(
"givenExplicitlyEnabledServerLoggingConfigurationShouldLogAccess-confdir" );
FileUtils.forceMkdir( confDir );
final File configFile = HTTPLoggingPreparednessRuleTest.createConfigFile(
HTTPLoggingPreparednessRuleTest.createLogbackConfigXml( logDirectory ), confDir );
final String query = "?explicitlyEnabled=" + UUID.randomUUID().toString();
NeoServer server = CommunityServerBuilder.server().withDefaultDatabaseTuning()
.withProperty( Configurator.HTTP_LOGGING, "true" )
.withProperty( Configurator.HTTP_LOG_CONFIG_LOCATION, configFile.getPath() )
.usingDatabaseDir( TargetDirectory.forTest( this.getClass() ).cleanDirectory(
"givenExplicitlyEnabledServerLoggingConfigurationShouldLogAccess-dbdir"
).getAbsolutePath() )
.build();
try
{
server.start();
FunctionalTestHelper functionalTestHelper = new FunctionalTestHelper( server );
// when
JaxRsResponse response = new RestRequest().get( functionalTestHelper.webAdminUri() + query );
assertEquals( 200, response.getStatus() );
response.close();
// then
assertEventually( "request appears in log", 5, new Condition()
{
public boolean evaluate()
{
return occursIn( query, new File( logDirectory, "http.log" ) );
}
} );
}
finally
{
server.stop();
}
}
@Test
public void givenConfigurationWithUnwritableLogDirectoryShouldFailToStartServer() throws Exception
{
// given
final File confDir = TargetDirectory.forTest( this.getClass() ).cleanDirectory( "confdir" );
final File unwritableLogDir = createUnwritableDirectory();
final File configFile = HTTPLoggingPreparednessRuleTest.createConfigFile(
HTTPLoggingPreparednessRuleTest.createLogbackConfigXml( unwritableLogDir ), confDir );
Configuration config = new MapBasedConfiguration();
config.setProperty( Configurator.HTTP_LOGGING, "true" );
config.setProperty( Configurator.HTTP_LOG_CONFIG_LOCATION, configFile.getPath() );
NeoServer server = CommunityServerBuilder.server().withDefaultDatabaseTuning()
.withPreflightTasks( new EnsurePreparedForHttpLogging( config ) )
.withProperty( Configurator.HTTP_LOGGING, "true" )
.withProperty( Configurator.HTTP_LOG_CONFIG_LOCATION, configFile.getPath() )
.usingDatabaseDir( confDir.getAbsolutePath() )
.build();
// when
try
{
server.start();
fail( "should have thrown exception" );
}
catch ( ServerStartupException e )
{
// then
assertThat( e.getMessage(),
containsString( String.format( "HTTP log directory [%s]",
unwritableLogDir.getAbsolutePath() ) ) );
}
finally
{
server.stop();
}
}
private File createUnwritableDirectory()
{
File file;
if ( osIsWindows() )
{
file = new File( "\\\\" + UUID.randomUUID().toString() + "\\http.log" );
}
else
{
TargetDirectory targetDirectory = TargetDirectory.forTest( this.getClass() );
file = targetDirectory.file( "unwritable-" + System.currentTimeMillis() );
assertTrue( "create directory to be unwritable", file.mkdirs() );
assertTrue( "mark directory as unwritable", file.setWritable( false, false ) );
}
return file;
}
private boolean occursIn( String lookFor, File file )
{
if ( !file.exists() )
{
return false;
}
Scanner scanner = null;
try
{
scanner = new Scanner( file );
while ( scanner.hasNext() )
{
if ( scanner.next().contains( lookFor ) )
{
return true;
}
}
return false;
}
catch ( FileNotFoundException e )
{
throw new RuntimeException( e );
}
finally
{
if ( scanner != null )
{
scanner.close();
}
}
}
}
| false
|
community_server_src_test_java_org_neo4j_server_web_logging_HTTPLoggingDocIT.java
|
1,777
|
public abstract class AbstractExclusiveServerWebadminTest extends ExclusiveServerTestBase {
protected static WebadminWebdriverLibrary wl;
private static WebDriverFacade webdriverFacade;
public static void setupWebdriver(NeoServer server) throws Exception {
webdriverFacade = new WebDriverFacade();
wl = new WebadminWebdriverLibrary( webdriverFacade, deriveBaseUri(server) );
}
public static void shutdownWebdriver() throws Exception {
webdriverFacade.quitBrowser();
}
private static String deriveBaseUri(NeoServer server)
{
String overrideBaseUri = System.getProperty( "webdriver.override.neo-server.baseuri" );
if ( StringUtils.isNotEmpty( overrideBaseUri )) {
return overrideBaseUri;
}
return server.baseUri().toString();
}
}
| false
|
community_server_src_webtest_java_org_neo4j_server_webadmin_AbstractExclusiveServerWebadminTest.java
|
1,778
|
public class Job
{
public final String query;
public final String assertion;
public final String comment;
public Job( final String query, final String assertion, final String comment )
{
this.query = query;
this.assertion = assertion;
this.comment = comment;
}
}
| false
|
community_shell_src_test_java_org_neo4j_shell_Documenter.java
|
1,779
|
public class ElementVisible extends BaseMatcher<WebDriver>
{
private final By by;
public static ElementVisible elementVisible(By by) {
return new ElementVisible(by);
}
public ElementVisible(By by) {
this.by = by;
}
@Override
public boolean matches( Object item )
{
if(item instanceof WebDriver) {
WebDriver d = (WebDriver)item;
try {
return ! d.findElement( by ).getCssValue( "display" ).equals( "none" );
} catch(NoSuchElementException e) {
return false;
} catch(StaleElementReferenceException e) {
return false;
}
}
return false;
}
@Override
public void describeTo( Description description )
{
description.appendText( "Element should be visible." );
}
}
| false
|
community_server_src_webtest_java_org_neo4j_server_webdriver_ElementVisible.java
|
1,780
|
public class ElementReference {
protected By selector;
protected WebdriverLibrary wl;
protected boolean matchLast;
public ElementReference(WebdriverLibrary wl, By selector) {
this(wl, selector, false);
}
public ElementReference(WebdriverLibrary wl, By selector, boolean matchLast) {
this.wl = wl;
this.selector = selector;
this.matchLast = matchLast;
}
public WebElement getElement() {
return wl.getWebElement( selector );
}
public WebElement findElement(By by) {
try {
return this.getElement().findElement(by);
} catch (StaleElementReferenceException e) {
return this.findElement(by);
}
}
public List<WebElement> findElements(By by) {
try {
return this.getElement().findElements(by);
} catch (StaleElementReferenceException e) {
return this.findElements(by);
}
}
public String getAttribute( String attributeName ) {
try {
return this.getElement().getAttribute(attributeName);
} catch (StaleElementReferenceException e) {
return this.getAttribute(attributeName);
}
}
public void click() {
try {
this.getElement().click();
} catch (StaleElementReferenceException e) {
this.click();
}
}
public String getValueOfCssProperty(String cssProperty) {
try {
return this.getElement().getCssValue(cssProperty);
} catch (StaleElementReferenceException e) {
return this.getValueOfCssProperty(cssProperty);
}
}
public void sendKeys(CharSequence ... keysToSend) {
try {
this.waitUntilVisible();
this.getElement().sendKeys(keysToSend);
} catch (StaleElementReferenceException e) {
this.sendKeys(keysToSend);
}
}
public String getValue() {
try {
return this.getElement().getAttribute("value");
} catch (StaleElementReferenceException e) {
return this.getValue();
}
}
public String getText() {
try {
this.waitUntilVisible();
return this.getElement().getText();
} catch (StaleElementReferenceException e) {
return this.getText();
}
}
public void clear() {
try {
this.getElement().clear();
} catch (StaleElementReferenceException e) {
this.clear();
}
}
public void waitUntilVisible() {
wl.waitForElementToAppear( selector );
}
public void waitUntilNotVisible() {
wl.waitForElementToDisappear( selector );
}
public void waitForAttributeToBe(String attr, String value) {
Condition<ElementReference> cond = new WebdriverCondition<ElementReference>( wl.getWebDriver(), elementAttributeIs(attr, value), this);
cond.waitUntilFulfilled(10000, "Attribute "+attr+" did not change to "+value+" within a reasonable time.");
}
public void waitForAttributeToChangeFrom(String attr, String value) {
Condition<ElementReference> cond = new WebdriverCondition<ElementReference>( wl.getWebDriver(), not( elementAttributeIs(attr, value) ), this);
cond.waitUntilFulfilled(10000, "Attribute "+attr+" did not change from "+value+" within a reasonable time.");
}
public void waitForTextToChangeFrom(String value) {
Condition<ElementReference> cond = new WebdriverCondition<ElementReference>( wl.getWebDriver(), not( elementTextIs(value) ), this);
cond.waitUntilFulfilled(10000, "Element text did not change from "+value+" within a reasonable time.");
}
public void waitForTextToChangeTo(String value) {
Condition<ElementReference> cond = new WebdriverCondition<ElementReference>( wl.getWebDriver(), elementTextIs(value), this);
cond.waitUntilFulfilled(10000, String.format( "Element text did not change to [%s] within a reasonable time - is still [%s]", value, getText() ) );
}
}
| false
|
community_server_src_webtest_java_org_neo4j_server_webdriver_ElementReference.java
|
1,781
|
public class ElementAttributeIs extends BaseMatcher<ElementReference>
{
private final String attr;
private final String value;
public static ElementAttributeIs elementAttributeIs(String attr, String value) {
return new ElementAttributeIs( attr, value );
}
public ElementAttributeIs(String attr, String value) {
this.attr = attr;
this.value = value;
}
@Override
public boolean matches( Object item )
{
if(item instanceof ElementReference) {
String currentValue = ((ElementReference)item).getAttribute(attr);
if ( (currentValue == null && value == null) || (currentValue != null && currentValue.matches(value))) {
return true;
}
}
return false;
}
@Override
public void describeTo( Description description )
{
description.appendText( "Element attribute "+ attr +" should match "+ value +"." );
}
}
| false
|
community_server_src_webtest_java_org_neo4j_server_webdriver_ElementAttributeIs.java
|
1,782
|
public class ConditionTimeoutException extends RuntimeException
{
/**
*
*/
private static final long serialVersionUID = 1L;
public ConditionTimeoutException(String msg) {
this(msg, null);
}
public ConditionTimeoutException(String msg, Throwable cause) {
super(msg, cause);
}
}
| false
|
community_server_src_webtest_java_org_neo4j_server_webdriver_ConditionTimeoutException.java
|
1,783
|
public class ConditionFailedException extends RuntimeException
{
/**
*
*/
private static final long serialVersionUID = 1L;
public ConditionFailedException(String msg, Throwable cause) {
super(msg, cause);
}
}
| false
|
community_server_src_webtest_java_org_neo4j_server_webdriver_ConditionFailedException.java
|
1,784
|
public class Condition<T>
{
private final T state;
private final Matcher<T> matcher;
public Condition(Matcher<T> matcher, T state) {
this.matcher = matcher;
this.state = state;
}
public boolean isFulfilled() {
return matcher.matches( state );
}
public void waitUntilFulfilled() {
waitUntilFulfilled( 1000 * 10 );
}
public void waitUntilFulfilled(long timeout) {
waitUntilFulfilled(timeout, "Condition was not fulfilled within the time limit ("+timeout+"ms)." );
}
public void waitUntilFulfilled(long timeout, String errorMessage) {
timeout = new Date().getTime() + timeout;
while((new Date().getTime()) < timeout)
{
try
{
Thread.sleep( 50 );
}
catch ( InterruptedException e )
{
throw new RuntimeException(e);
}
if ( isFulfilled() ) {
return;
}
}
throw new ConditionTimeoutException( errorMessage );
}
}
| false
|
community_server_src_webtest_java_org_neo4j_server_webdriver_Condition.java
|
1,785
|
public class BrowserUrlIs extends BaseMatcher<WebDriver>
{
private final String url;
public static BrowserUrlIs browserUrlIs(String url) {
return new BrowserUrlIs( url );
}
public BrowserUrlIs(String url) {
this.url = url;
}
@Override
public boolean matches( Object item )
{
if(item instanceof WebDriver) {
return ((WebDriver)item).getCurrentUrl().matches( url );
}
return false;
}
@Override
public void describeTo( Description description )
{
description.appendText( "Web browser url should be " + url + "." );
}
}
| false
|
community_server_src_webtest_java_org_neo4j_server_webdriver_BrowserUrlIs.java
|
1,786
|
public class BrowserTitleIs extends BaseMatcher<WebDriver>
{
private final String title;
public static final BrowserTitleIs browserTitleIs(String title) {
return new BrowserTitleIs( title );
}
public BrowserTitleIs(String title) {
this.title = title;
}
@Override
public void describeTo( Description description )
{
description.appendText( "Web browser title should be " + title + "." );
}
@Override
public boolean matches( Object wd )
{
if(wd instanceof WebDriver) {
return ((WebDriver)wd).getTitle().matches(title );
} else {
return false;
}
}
}
| false
|
community_server_src_webtest_java_org_neo4j_server_webdriver_BrowserTitleIs.java
|
1,787
|
{
@Override
protected void serialize( MappingSerializer resourceSerializer )
{
for ( Map.Entry<String, String> entry : uris.entrySet() )
{
resourceSerializer.putUri( entry.getKey(), entry.getValue() );
}
for ( Map.Entry<String, String> entry : templates.entrySet() )
{
resourceSerializer.putUriTemplate( entry.getKey(), entry.getValue() );
}
}
} );
| false
|
community_server_src_main_java_org_neo4j_server_webadmin_rest_representations_ServiceDefinitionRepresentation.java
|
1,788
|
public class ServiceDefinitionRepresentation extends MappingRepresentation
{
private final HashMap<String, String> uris;
private final HashMap<String, String> templates;
private final String basePath;
public ServiceDefinitionRepresentation( String basePath )
{
super( "service-definition" );
this.basePath = basePath;
uris = new HashMap<String, String>();
templates = new HashMap<String, String>();
}
public void resourceUri( String name, String subPath )
{
uris.put( name, relative( subPath ) );
}
public void resourceTemplate( String name, String subPath )
{
templates.put( name, relative( subPath ) );
}
private String relative( String subPath )
{
if ( basePath.endsWith( "/" ) )
{
if ( subPath.startsWith( "/" ) ) return basePath + subPath.substring( 1 );
}
else if ( !subPath.startsWith( "/" ) ) return basePath + "/" + subPath;
return basePath + subPath;
}
@Override
public void serialize( MappingSerializer serializer )
{
serializer.putMapping( "resources", new MappingRepresentation( "resources" )
{
@Override
protected void serialize( MappingSerializer resourceSerializer )
{
for ( Map.Entry<String, String> entry : uris.entrySet() )
{
resourceSerializer.putUri( entry.getKey(), entry.getValue() );
}
for ( Map.Entry<String, String> entry : templates.entrySet() )
{
resourceSerializer.putUriTemplate( entry.getKey(), entry.getValue() );
}
}
} );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_webadmin_rest_representations_ServiceDefinitionRepresentation.java
|
1,789
|
public class ServerRootRepresentationTest
{
@Test
public void shouldProvideAListOfServiceUris() throws Exception
{
ConsoleService consoleService = new ConsoleService( null, mockDatabase(), DEV_NULL, null );
ServerRootRepresentation srr = new ServerRootRepresentation( new URI( "http://example.org:9999" ),
Collections.<AdvertisableService>singletonList( consoleService ) );
Map<String, Map<String, String>> map = srr.serialize();
assertNotNull( map.get( "services" ) );
assertThat( map.get( "services" )
.get( consoleService.getName() ), containsString( consoleService.getServerPath() ) );
}
private Database mockDatabase()
{
Database db = mock( Database.class );
when( db.getLogging() ).thenReturn( DEV_NULL );
return db;
}
}
| false
|
community_server_src_test_java_org_neo4j_server_webadmin_rest_representations_ServerRootRepresentationTest.java
|
1,790
|
{
@Override
protected void serialize( MappingSerializer serializer )
{
for ( Map.Entry<String, String> entry : services.entrySet() )
{
serializer.putString( entry.getKey(), entry.getValue() );
}
}
};
| false
|
community_server_src_main_java_org_neo4j_server_webadmin_rest_representations_ServerRootRepresentation.java
|
1,791
|
public class ServerRootRepresentation extends MappingRepresentation
{
private HashMap<String, String> services = new HashMap<String, String>();
public ServerRootRepresentation( URI baseUri, Iterable<AdvertisableService> advertisableServices )
{
super( "services" );
for ( AdvertisableService svc : advertisableServices )
{
services.put( svc.getName(), baseUri.toString() + svc.getServerPath() );
}
}
public Map<String, Map<String, String>> serialize()
{
HashMap<String, Map<String, String>> result = new HashMap<String, Map<String, String>>();
result.put( "services", services );
return result;
}
@Override
protected void serialize( MappingSerializer serializer )
{
MappingRepresentation apa = new MappingRepresentation( "services" )
{
@Override
protected void serialize( MappingSerializer serializer )
{
for ( Map.Entry<String, String> entry : services.entrySet() )
{
serializer.putString( entry.getKey(), entry.getValue() );
}
}
};
serializer.putMapping( "services", apa );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_webadmin_rest_representations_ServerRootRepresentation.java
|
1,792
|
{
@Override
protected void serialize( MappingSerializer serializer )
{
String[] dsNames = rrdData.getDsNames();
for ( int i = 0, l = dsNames.length; i < l; i++ )
{
serializer.putList( dsNames[i], ListRepresentation.numbers( rrdData.getValues( i ) ) );
}
}
};
| false
|
community_server_src_main_java_org_neo4j_server_webadmin_rest_representations_RrdDataRepresentation.java
|
1,793
|
public class RrdDataRepresentation extends ObjectRepresentation
{
private final FetchData rrdData;
public RrdDataRepresentation( FetchData rrdData )
{
super( "rrd-data" );
this.rrdData = rrdData;
}
@Mapping( "start_time" )
public ValueRepresentation getStartTime()
{
return ValueRepresentation.number( rrdData.getFirstTimestamp() );
}
@Mapping( "end_time" )
public ValueRepresentation getEndTime()
{
return ValueRepresentation.number( rrdData.getLastTimestamp() );
}
@Mapping( "timestamps" )
public ListRepresentation getTimestamps()
{
return ListRepresentation.numbers( rrdData.getTimestamps() );
}
@Mapping( "data" )
public MappingRepresentation getDatasources()
{
return new MappingRepresentation( "datasources" )
{
@Override
protected void serialize( MappingSerializer serializer )
{
String[] dsNames = rrdData.getDsNames();
for ( int i = 0, l = dsNames.length; i < l; i++ )
{
serializer.putList( dsNames[i], ListRepresentation.numbers( rrdData.getValues( i ) ) );
}
}
};
}
}
| false
|
community_server_src_main_java_org_neo4j_server_webadmin_rest_representations_RrdDataRepresentation.java
|
1,794
|
public class NameDescriptionValueRepresentation extends ObjectRepresentation
{
private String name;
private String description;
private Representation value;
public NameDescriptionValueRepresentation( String name, String description, Representation value )
{
super( "nameDescriptionValue" );
this.name = name;
this.description = description;
this.value = value;
}
@Mapping( "name" )
public ValueRepresentation getName()
{
return ValueRepresentation.string( name );
}
@Mapping( "description" )
public ValueRepresentation getDescription()
{
return ValueRepresentation.string( description );
}
@Mapping( "value" )
public Representation getValue()
{
return value;
}
}
| false
|
community_server_src_main_java_org_neo4j_server_webadmin_rest_representations_NameDescriptionValueRepresentation.java
|
1,795
|
{
@Override
protected Representation underlyingObjectToObject( MBeanAttributeInfo attrInfo )
{
return new JmxAttributeRepresentation( beanName, attrInfo );
}
} );
| false
|
community_server_src_main_java_org_neo4j_server_webadmin_rest_representations_JmxMBeanRepresentation.java
|
1,796
|
public class JmxMBeanRepresentation extends ObjectRepresentation
{
protected ObjectName beanName;
protected MBeanServer jmxServer = ManagementFactory.getPlatformMBeanServer();
public JmxMBeanRepresentation( ObjectName beanInstance )
{
super( "jmxBean" );
this.beanName = beanInstance;
}
@Mapping( "name" )
public ValueRepresentation getName()
{
return ValueRepresentation.string( beanName.getCanonicalName() );
}
@Mapping( "url" )
public ValueRepresentation getUrl()
{
try
{
String value = URLEncoder.encode( beanName.toString(), "UTF-8" )
.replace( "%3A", "/" );
return ValueRepresentation.string( value );
}
catch ( UnsupportedEncodingException e )
{
throw new RuntimeException( "Could not encode string as UTF-8", e );
}
}
@Mapping( "description" )
public ValueRepresentation getDescription() throws IntrospectionException, InstanceNotFoundException,
ReflectionException
{
MBeanInfo beanInfo = jmxServer.getMBeanInfo( beanName );
return ValueRepresentation.string( beanInfo.getDescription() );
}
@Mapping( "attributes" )
public ListRepresentation getAttributes() throws IntrospectionException, InstanceNotFoundException,
ReflectionException
{
MBeanInfo beanInfo = jmxServer.getMBeanInfo( beanName );
return new ListRepresentation( "jmxAttribute", new IterableWrapper<Representation, MBeanAttributeInfo>(
Arrays.asList( beanInfo.getAttributes() ) )
{
@Override
protected Representation underlyingObjectToObject( MBeanAttributeInfo attrInfo )
{
return new JmxAttributeRepresentation( beanName, attrInfo );
}
} );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_webadmin_rest_representations_JmxMBeanRepresentation.java
|
1,797
|
public class JmxDomainRepresentation extends ObjectRepresentation
{
protected ArrayList<JmxMBeanRepresentation> beans = new ArrayList<JmxMBeanRepresentation>();
protected String domainName;
public JmxDomainRepresentation( String name )
{
super( "jmxDomain" );
this.domainName = name;
}
@Mapping( "domain" )
public ValueRepresentation getDomainName()
{
return string( this.domainName );
}
@Mapping( "beans" )
public ListRepresentation getBeans()
{
return new ListRepresentation( "bean", beans );
}
public void addBean( ObjectName bean )
{
beans.add( new JmxMBeanRepresentation( bean ) );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_webadmin_rest_representations_JmxDomainRepresentation.java
|
1,798
|
public class JmxCompositeDataRepresentation extends ObjectRepresentation
{
protected CompositeData data;
private static final RepresentationDispatcher REPRESENTATION_DISPATCHER = new JmxAttributeRepresentationDispatcher();
public JmxCompositeDataRepresentation( CompositeData data )
{
super( "jmxCompositeData" );
this.data = data;
}
@Mapping( "type" )
public ValueRepresentation getType()
{
return ValueRepresentation.string( data.getCompositeType()
.getTypeName() );
}
@Mapping( "description" )
public ValueRepresentation getDescription()
{
return ValueRepresentation.string( data.getCompositeType()
.getDescription() );
}
@Mapping( "value" )
public ListRepresentation getValue()
{
ArrayList<Representation> values = new ArrayList<Representation>();
for ( Object key : data.getCompositeType()
.keySet() )
{
String name = key.toString();
String description = data.getCompositeType()
.getDescription( name );
Representation value = REPRESENTATION_DISPATCHER.dispatch( data.get( name ), "" );
values.add( new NameDescriptionValueRepresentation( name, description, value ) );
}
return new ListRepresentation( "value", values );
}
}
| false
|
community_server_src_main_java_org_neo4j_server_webadmin_rest_representations_JmxCompositeDataRepresentation.java
|
1,799
|
public class ElementTextIs extends BaseMatcher<ElementReference>
{
private final String value;
public static ElementTextIs elementTextIs( String value) {
return new ElementTextIs( value );
}
public ElementTextIs(String value) {
this.value = value;
}
@Override
public boolean matches( Object item )
{
if(item instanceof ElementReference) {
String currentValue = ((ElementReference)item).getText();
if ( (currentValue == null && value == null) || (currentValue != null && currentValue.matches(value))) {
return true;
}
}
return false;
}
@Override
public void describeTo( Description description )
{
description.appendText( "Element text should be "+ value +"." );
}
}
| false
|
community_server_src_webtest_java_org_neo4j_server_webdriver_ElementTextIs.java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.