Unnamed: 0
int64 0
1.77k
| func
stringlengths 14
223k
| target
bool 2
classes | project
stringlengths 61
138
|
---|---|---|---|
0 | public class BerkeleyStorageSetup extends StorageSetup {
public static ModifiableConfiguration getBerkeleyJEConfiguration(String dir) {
return buildConfiguration()
.set(STORAGE_BACKEND,"berkeleyje")
.set(STORAGE_DIRECTORY, dir);
}
public static ModifiableConfiguration getBerkeleyJEConfiguration() {
return getBerkeleyJEConfiguration(getHomeDir());
}
public static WriteConfiguration getBerkeleyJEGraphConfiguration() {
return getBerkeleyJEConfiguration().getConfiguration();
}
public static ModifiableConfiguration getBerkeleyJEPerformanceConfiguration() {
return getBerkeleyJEConfiguration()
.set(STORAGE_TRANSACTIONAL,false)
.set(TX_CACHE_SIZE,1000);
}
} | false | titan-berkeleyje_src_test_java_com_thinkaurelius_titan_BerkeleyStorageSetup.java |
1 | public class CassandraStorageSetup {
public static final String CONFDIR_SYSPROP = "test.cassandra.confdir";
public static final String DATADIR_SYSPROP = "test.cassandra.datadir";
private static volatile Paths paths;
private static final Logger log = LoggerFactory.getLogger(CassandraStorageSetup.class);
private static synchronized Paths getPaths() {
if (null == paths) {
String yamlPath = "file://" + loadAbsoluteDirectoryPath("conf", CONFDIR_SYSPROP, true) + File.separator + "cassandra.yaml";
String dataPath = loadAbsoluteDirectoryPath("data", DATADIR_SYSPROP, false);
paths = new Paths(yamlPath, dataPath);
}
return paths;
}
private static ModifiableConfiguration getGenericConfiguration(String ks, String backend) {
ModifiableConfiguration config = buildConfiguration();
config.set(CASSANDRA_KEYSPACE, cleanKeyspaceName(ks));
log.debug("Set keyspace name: {}", config.get(CASSANDRA_KEYSPACE));
config.set(PAGE_SIZE,500);
config.set(CONNECTION_TIMEOUT, new StandardDuration(60L, TimeUnit.SECONDS));
config.set(STORAGE_BACKEND, backend);
return config;
}
public static ModifiableConfiguration getEmbeddedConfiguration(String ks) {
ModifiableConfiguration config = getGenericConfiguration(ks, "embeddedcassandra");
config.set(STORAGE_CONF_FILE, getPaths().yamlPath);
return config;
}
public static ModifiableConfiguration getEmbeddedCassandraPartitionConfiguration(String ks) {
ModifiableConfiguration config = getEmbeddedConfiguration(ks);
config.set(CLUSTER_PARTITION, true);
config.set(IDS_FLUSH,false);
return config;
}
public static WriteConfiguration getEmbeddedGraphConfiguration(String ks) {
return getEmbeddedConfiguration(ks).getConfiguration();
}
public static WriteConfiguration getEmbeddedCassandraPartitionGraphConfiguration(String ks) {
return getEmbeddedConfiguration(ks).getConfiguration();
}
public static ModifiableConfiguration getAstyanaxConfiguration(String ks) {
return getGenericConfiguration(ks, "astyanax");
}
public static ModifiableConfiguration getAstyanaxSSLConfiguration(String ks) {
return enableSSL(getGenericConfiguration(ks, "astyanax"));
}
public static WriteConfiguration getAstyanaxGraphConfiguration(String ks) {
return getAstyanaxConfiguration(ks).getConfiguration();
}
public static ModifiableConfiguration getCassandraConfiguration(String ks) {
return getGenericConfiguration(ks, "cassandra");
}
public static WriteConfiguration getCassandraGraphConfiguration(String ks) {
return getCassandraConfiguration(ks).getConfiguration();
}
public static ModifiableConfiguration getCassandraThriftConfiguration(String ks) {
return getGenericConfiguration(ks, "cassandrathrift");
}
public static ModifiableConfiguration getCassandraThriftSSLConfiguration(String ks) {
return enableSSL(getGenericConfiguration(ks, "cassandrathrift"));
}
public static WriteConfiguration getCassandraThriftGraphConfiguration(String ks) {
return getCassandraThriftConfiguration(ks).getConfiguration();
}
/**
* Load cassandra.yaml and data paths from the environment or from default
* values if nothing is set in the environment, then delete all existing
* data, and finally start Cassandra.
* <p>
* This method is idempotent. Calls after the first have no effect aside
* from logging statements.
*/
public static void startCleanEmbedded() {
startCleanEmbedded(getPaths());
}
/*
* Cassandra only accepts keyspace names 48 characters long or shorter made
* up of alphanumeric characters and underscores.
*/
public static String cleanKeyspaceName(String raw) {
Preconditions.checkNotNull(raw);
Preconditions.checkArgument(0 < raw.length());
if (48 < raw.length() || raw.matches("[^a-zA-Z_]")) {
return "strhash" + String.valueOf(Math.abs(raw.hashCode()));
} else {
return raw;
}
}
private static ModifiableConfiguration enableSSL(ModifiableConfiguration mc) {
mc.set(AbstractCassandraStoreManager.SSL_ENABLED, true);
mc.set(STORAGE_HOSTS, new String[]{ "localhost" });
mc.set(AbstractCassandraStoreManager.SSL_TRUSTSTORE_LOCATION,
Joiner.on(File.separator).join("target", "cassandra", "conf", "localhost-murmur-ssl", "test.truststore"));
mc.set(AbstractCassandraStoreManager.SSL_TRUSTSTORE_PASSWORD, "cassandra");
return mc;
}
private static void startCleanEmbedded(Paths p) {
if (!CassandraDaemonWrapper.isStarted()) {
try {
FileUtils.deleteDirectory(new File(p.dataPath));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
CassandraDaemonWrapper.start(p.yamlPath);
}
private static String loadAbsoluteDirectoryPath(String name, String prop, boolean mustExistAndBeAbsolute) {
String s = System.getProperty(prop);
if (null == s) {
s = Joiner.on(File.separator).join(System.getProperty("user.dir"), "target", "cassandra", name, "localhost-bop");
log.info("Set default Cassandra {} directory path {}", name, s);
} else {
log.info("Loaded Cassandra {} directory path {} from system property {}", new Object[] { name, s, prop });
}
if (mustExistAndBeAbsolute) {
File dir = new File(s);
Preconditions.checkArgument(dir.isDirectory(), "Path %s must be a directory", s);
Preconditions.checkArgument(dir.isAbsolute(), "Path %s must be absolute", s);
}
return s;
}
private static class Paths {
private final String yamlPath;
private final String dataPath;
public Paths(String yamlPath, String dataPath) {
this.yamlPath = yamlPath;
this.dataPath = dataPath;
}
}
} | false | titan-cassandra_src_test_java_com_thinkaurelius_titan_CassandraStorageSetup.java |
2 | private static class Paths {
private final String yamlPath;
private final String dataPath;
public Paths(String yamlPath, String dataPath) {
this.yamlPath = yamlPath;
this.dataPath = dataPath;
}
} | false | titan-cassandra_src_test_java_com_thinkaurelius_titan_CassandraStorageSetup.java |
3 | public abstract class DaemonRunner<S> {
private static final Logger log =
LoggerFactory.getLogger(DaemonRunner.class);
private Thread killerHook;
protected abstract String getDaemonShortName();
protected abstract void killImpl(final S stat) throws IOException;
protected abstract S startImpl() throws IOException;
protected abstract S readStatusFromDisk();
/**
* Read daemon status from disk, then try to start the dameon
* if the status file says it is stopped. Do nothing if the
* status read from disk says the daemon is running.
*
* After succesfully starting the daemon (no exceptions from
* {@link #startImpl()}, register a shutdown hook with the VM
* that will call {@link #killImpl(S)} on shutdown.
*
* @return status representing the daemon, either just-started
* or already running
*/
public synchronized S start() {
S stat = readStatusFromDisk();
if (stat != null) {
log.info("{} already started", getDaemonShortName());
return stat;
}
try {
stat = startImpl();
} catch (IOException e) {
throw new RuntimeException(e);
}
registerKillerHook(stat);
return stat;
}
/**
* Read daemon status from disk, then try to kill the daemon
* if the status file says it is running. Do nothing if the
* status read from disk says the daemon is stopped.
*/
public synchronized void stop() {
S stat = readStatusFromDisk();
if (null == stat) {
log.info("{} is not running", getDaemonShortName());
return;
}
killAndUnregisterHook(stat);
}
private synchronized void registerKillerHook(final S stat) {
if (null != killerHook) {
log.debug("Daemon killer hook already registered: {}", killerHook);
return;
}
killerHook = new Thread() {
public void run() {
killAndUnregisterHook(stat);
}
};
Runtime.getRuntime().addShutdownHook(killerHook);
log.debug("Registered daemon killer hook: {}", killerHook);
}
private synchronized void killAndUnregisterHook(final S stat) {
try {
killImpl(stat);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (null != killerHook) {
try {
Runtime.getRuntime().removeShutdownHook(killerHook);
log.debug("Unregistered killer hook: {}", killerHook);
} catch (IllegalStateException e) {
/* Can receive "java.lang.IllegalStateException: Shutdown in progress"
* when called from JVM shutdown (as opposed to called from the stop method).
*/
log.debug("Could not unregister killer hook: {}", e);
}
killerHook = null;
}
}
/**
* Run the parameter as an external process. Returns if the command starts
* without throwing an exception and returns exit status 0. Throws an
* exception if there's any problem invoking the command or if it does not
* return zero exit status.
*
* Blocks indefinitely while waiting for the command to complete.
*
* @param argv
* passed directly to {@link ProcessBuilder}'s constructor
*/
protected static void runCommand(String... argv) {
final String cmd = Joiner.on(" ").join(argv);
log.info("Executing {}", cmd);
ProcessBuilder pb = new ProcessBuilder(argv);
pb.redirectErrorStream(true);
Process startup;
try {
startup = pb.start();
} catch (IOException e) {
throw new RuntimeException(e);
}
StreamLogger sl = new StreamLogger(startup.getInputStream());
sl.setDaemon(true);
sl.start();
try {
int exitcode = startup.waitFor(); // wait for script to return
if (0 == exitcode) {
log.info("Command \"{}\" exited with status 0", cmd);
} else {
throw new RuntimeException("Command \"" + cmd + "\" exited with status " + exitcode);
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
try {
sl.join(1000L);
} catch (InterruptedException e) {
log.warn("Failed to cleanup stdin handler thread after running command \"{}\"", cmd, e);
}
}
/*
* This could be retired in favor of ProcessBuilder.Redirect when we move to
* source level 1.7.
*/
private static class StreamLogger extends Thread {
private final BufferedReader reader;
private static final Logger log =
LoggerFactory.getLogger(StreamLogger.class);
private StreamLogger(InputStream is) {
this.reader = new BufferedReader(new InputStreamReader(is));
}
@Override
public void run() {
String line;
try {
while (null != (line = reader.readLine())) {
log.info("> {}", line);
if (Thread.currentThread().isInterrupted()) {
break;
}
}
log.info("End of stream.");
} catch (IOException e) {
log.error("Unexpected IOException while reading stream {}", reader, e);
}
}
}
} | false | titan-test_src_main_java_com_thinkaurelius_titan_DaemonRunner.java |
4 | killerHook = new Thread() {
public void run() {
killAndUnregisterHook(stat);
}
}; | false | titan-test_src_main_java_com_thinkaurelius_titan_DaemonRunner.java |
5 | private static class StreamLogger extends Thread {
private final BufferedReader reader;
private static final Logger log =
LoggerFactory.getLogger(StreamLogger.class);
private StreamLogger(InputStream is) {
this.reader = new BufferedReader(new InputStreamReader(is));
}
@Override
public void run() {
String line;
try {
while (null != (line = reader.readLine())) {
log.info("> {}", line);
if (Thread.currentThread().isInterrupted()) {
break;
}
}
log.info("End of stream.");
} catch (IOException e) {
log.error("Unexpected IOException while reading stream {}", reader, e);
}
}
} | false | titan-test_src_main_java_com_thinkaurelius_titan_DaemonRunner.java |
6 | public class HBaseStatus {
private static final Logger log =
LoggerFactory.getLogger(HBaseStatus.class);
private final File file;
private final String version;
private HBaseStatus(File file, String version) {
Preconditions.checkNotNull(file);
Preconditions.checkNotNull(version);
this.file = file;
this.version = version;
}
public String getVersion() {
return version;
}
public File getFile() {
return file;
}
public String getScriptDir() {
return HBaseStorageSetup.getScriptDirForHBaseVersion(version);
}
public String getConfDir() {
return HBaseStorageSetup.getConfDirForHBaseVersion(version);
}
public static HBaseStatus read(String path) {
File pid = new File(path);
if (!pid.exists()) {
log.info("HBase pidfile {} does not exist", path);
return null;
}
BufferedReader pidReader = null;
try {
pidReader = new BufferedReader(new FileReader(pid));
HBaseStatus s = parsePidFile(pid, pidReader);
log.info("Read HBase status from {}", path);
return s;
} catch (HBasePidfileParseException e) {
log.warn("Assuming HBase is not running", e);
} catch (IOException e) {
log.warn("Assuming HBase is not running", e);
} finally {
IOUtils.closeQuietly(pidReader);
}
return null;
}
public static HBaseStatus write(String path, String hbaseVersion) {
File f = new File(path);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(path);
fos.write(String.format("%s", hbaseVersion).getBytes());
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
IOUtils.closeQuietly(fos);
}
return new HBaseStatus(f, hbaseVersion);
}
private static HBaseStatus parsePidFile(File f, BufferedReader br) throws HBasePidfileParseException, IOException {
String l = br.readLine();
if (null == l || "".equals(l.trim())) {
throw new HBasePidfileParseException("Empty HBase statusfile " + f);
}
HBaseStatus stat = new HBaseStatus(f, l.trim());
return stat;
}
private static class HBasePidfileParseException extends Exception {
private static final long serialVersionUID = 1L;
public HBasePidfileParseException(String message) {
super(message);
}
}
} | false | titan-hbase-parent_titan-hbase-core_src_test_java_com_thinkaurelius_titan_HBaseStatus.java |
7 | private static class HBasePidfileParseException extends Exception {
private static final long serialVersionUID = 1L;
public HBasePidfileParseException(String message) {
super(message);
}
} | false | titan-hbase-parent_titan-hbase-core_src_test_java_com_thinkaurelius_titan_HBaseStatus.java |
8 | public class HBaseStorageSetup {
private static final Logger log = LoggerFactory.getLogger(HBaseStorageSetup.class);
// hbase config for testing
public static final String HBASE_PARENT_DIR_PROP = "test.hbase.parentdir";
private static final Pattern HBASE_SUPPORTED_VERSION_PATTERN = Pattern.compile("^0\\.(9[468])\\..*");
private static final String HBASE_PARENT_DIR;
private static final String HBASE_TARGET_VERSION = VersionInfo.getVersion();
static {
String parentDir = "..";
String tmp = System.getProperty(HBASE_PARENT_DIR_PROP);
if (null != tmp) {
parentDir = tmp;
}
HBASE_PARENT_DIR = parentDir;
}
private static final String HBASE_STAT_FILE = "/tmp/titan-hbase-test-daemon.stat";
private volatile static HBaseStatus HBASE = null;
public static String getScriptDirForHBaseVersion(String hv) {
return getDirForHBaseVersion(hv, "bin");
}
public static String getConfDirForHBaseVersion(String hv) {
return getDirForHBaseVersion(hv, "conf");
}
public static String getDirForHBaseVersion(String hv, String lastSubdir) {
Matcher m = HBASE_SUPPORTED_VERSION_PATTERN.matcher(hv);
if (m.matches()) {
String minor = m.group(1);
String result = String.format("%s%stitan-hbase-0%s/%s/", HBASE_PARENT_DIR, File.separator, minor, lastSubdir);
log.debug("Built {} path for HBase version {}: {}", lastSubdir, hv, result);
return result;
} else {
throw new RuntimeException("Unsupported HBase test version " + hv + " does not match pattern " + HBASE_SUPPORTED_VERSION_PATTERN);
}
}
public static ModifiableConfiguration getHBaseConfiguration() {
ModifiableConfiguration config = GraphDatabaseConfiguration.buildConfiguration();
config.set(GraphDatabaseConfiguration.STORAGE_BACKEND, "hbase");
config.set(GraphDatabaseConfiguration.CLUSTER_PARTITION, true);
config.set(GraphDatabaseConfiguration.TIMESTAMP_PROVIDER, HBaseStoreManager.PREFERRED_TIMESTAMPS);
config.set(SimpleBulkPlacementStrategy.CONCURRENT_PARTITIONS, 1);
// config.set(GraphDatabaseConfiguration.STORAGE_NS.getName()+"."+HBaseStoreManager.HBASE_CONFIGURATION_NAMESPACE+
// ".hbase.zookeeper.quorum","localhost");
// config.set(GraphDatabaseConfiguration.STORAGE_NS.getName()+"."+HBaseStoreManager.HBASE_CONFIGURATION_NAMESPACE+
// "hbase.zookeeper.property.clientPort",2181);
return config;
}
public static WriteConfiguration getHBaseGraphConfiguration() {
return getHBaseConfiguration().getConfiguration();
}
/**
* Starts the HBase version described by {@link #HBASE_TARGET_VERSION}
*
* @return a status object describing a successfully-started HBase daemon
* @throws IOException
* passed-through
* @throws RuntimeException
* if starting HBase fails for any other reason
*/
public synchronized static HBaseStatus startHBase() throws IOException {
if (HBASE != null) {
log.info("HBase already started");
return HBASE;
}
killIfRunning();
deleteData();
log.info("Starting HBase");
String scriptPath = getScriptDirForHBaseVersion(HBASE_TARGET_VERSION) + "/hbase-daemon.sh";
runCommand(scriptPath, "--config", getConfDirForHBaseVersion(HBASE_TARGET_VERSION), "start", "master");
HBASE = HBaseStatus.write(HBASE_STAT_FILE, HBASE_TARGET_VERSION);
registerKillerHook(HBASE);
return HBASE;
}
/**
* Check whether {@link #HBASE_STAT_FILE} describes an HBase daemon. If so,
* kill it. Otherwise, do nothing.
*/
public synchronized static void killIfRunning() {
HBaseStatus stat = HBaseStatus.read(HBASE_STAT_FILE);
if (null == stat) {
log.info("HBase is not running");
return;
}
shutdownHBase(stat);
}
/**
* Delete HBase data under the current working directory.
*/
private synchronized static void deleteData() {
try {
// please keep in sync with HBASE_CONFIG_DIR/hbase-site.xml, reading HBase XML config is huge pain.
File hbaseRoot = new File("./target/hbase-root");
File zookeeperDataDir = new File("./target/zk-data");
if (hbaseRoot.exists()) {
log.info("Deleting {}", hbaseRoot);
FileUtils.deleteDirectory(hbaseRoot);
}
if (zookeeperDataDir.exists()) {
log.info("Deleting {}", zookeeperDataDir);
FileUtils.deleteDirectory(zookeeperDataDir);
}
} catch (IOException e) {
throw new RuntimeException("Failed to delete old HBase test data directories", e);
}
}
/**
* Register a shutdown hook with the JVM that attempts to kill the external
* HBase daemon
*
* @param stat
* the HBase daemon to kill
*/
private static void registerKillerHook(final HBaseStatus stat) {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
shutdownHBase(stat);
}
});
}
/**
* Runs the {@code hbase-daemon.sh stop master} script corresponding to the
* HBase version described by the parameter.
*
* @param stat
* the running HBase daemon to stop
*/
private synchronized static void shutdownHBase(HBaseStatus stat) {
log.info("Shutting down HBase...");
// First try graceful shutdown through the script...
runCommand(stat.getScriptDir() + "/hbase-daemon.sh", "--config", stat.getConfDir(), "stop", "master");
log.info("Shutdown HBase");
stat.getFile().delete();
log.info("Deleted {}", stat.getFile());
HBASE = null;
}
/**
* Run the parameter as an external process. Returns if the command starts
* without throwing an exception and returns exit status 0. Throws an
* exception if there's any problem invoking the command or if it does not
* return zero exit status.
*
* Blocks indefinitely while waiting for the command to complete.
*
* @param argv
* passed directly to {@link ProcessBuilder}'s constructor
*/
private static void runCommand(String... argv) {
final String cmd = Joiner.on(" ").join(argv);
log.info("Executing {}", cmd);
ProcessBuilder pb = new ProcessBuilder(argv);
pb.redirectErrorStream(true);
Process startup;
try {
startup = pb.start();
} catch (IOException e) {
throw new RuntimeException(e);
}
StreamLogger sl = new StreamLogger(startup.getInputStream());
sl.setDaemon(true);
sl.start();
try {
int exitcode = startup.waitFor(); // wait for script to return
if (0 == exitcode) {
log.info("Command \"{}\" exited with status 0", cmd);
} else {
throw new RuntimeException("Command \"" + cmd + "\" exited with status " + exitcode);
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
try {
sl.join(1000L);
} catch (InterruptedException e) {
log.warn("Failed to cleanup stdin handler thread after running command \"{}\"", cmd, e);
}
}
/*
* This could be retired in favor of ProcessBuilder.Redirect when we move to
* source level 1.7.
*/
private static class StreamLogger extends Thread {
private final BufferedReader reader;
private static final Logger log =
LoggerFactory.getLogger(StreamLogger.class);
private StreamLogger(InputStream is) {
this.reader = new BufferedReader(new InputStreamReader(is));
}
@Override
public void run() {
String line;
try {
while (null != (line = reader.readLine())) {
log.info("> {}", line);
if (Thread.currentThread().isInterrupted()) {
break;
}
}
log.info("End of stream.");
} catch (IOException e) {
log.error("Unexpected IOException while reading stream {}", reader, e);
}
}
}
} | false | titan-hbase-parent_titan-hbase-core_src_test_java_com_thinkaurelius_titan_HBaseStorageSetup.java |
9 | Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
shutdownHBase(stat);
}
}); | false | titan-hbase-parent_titan-hbase-core_src_test_java_com_thinkaurelius_titan_HBaseStorageSetup.java |
10 | private static class StreamLogger extends Thread {
private final BufferedReader reader;
private static final Logger log =
LoggerFactory.getLogger(StreamLogger.class);
private StreamLogger(InputStream is) {
this.reader = new BufferedReader(new InputStreamReader(is));
}
@Override
public void run() {
String line;
try {
while (null != (line = reader.readLine())) {
log.info("> {}", line);
if (Thread.currentThread().isInterrupted()) {
break;
}
}
log.info("End of stream.");
} catch (IOException e) {
log.error("Unexpected IOException while reading stream {}", reader, e);
}
}
} | false | titan-hbase-parent_titan-hbase-core_src_test_java_com_thinkaurelius_titan_HBaseStorageSetup.java |
11 | public class StorageSetup {
//############ UTILITIES #############
public static final String getHomeDir(String subdir) {
String homedir = System.getProperty("titan.testdir");
if (null == homedir) {
homedir = "target" + File.separator + "db";
}
if (subdir!=null && !StringUtils.isEmpty(subdir)) homedir += File.separator + subdir;
File homefile = new File(homedir);
if (!homefile.exists()) homefile.mkdirs();
return homedir;
}
public static final String getHomeDir() {
return getHomeDir(null);
}
public static final File getHomeDirFile() {
return getHomeDirFile(null);
}
public static final File getHomeDirFile(String subdir) {
return new File(getHomeDir(subdir));
}
public static final void deleteHomeDir() {
deleteHomeDir(null);
}
public static final void deleteHomeDir(String subdir) {
File homeDirFile = getHomeDirFile(subdir);
// Make directory if it doesn't exist
if (!homeDirFile.exists())
homeDirFile.mkdirs();
boolean success = IOUtils.deleteFromDirectory(homeDirFile);
if (!success) throw new IllegalStateException("Could not remove " + homeDirFile);
}
public static TitanGraph getInMemoryGraph() {
return TitanFactory.open(buildConfiguration().set(STORAGE_BACKEND,"inmemory"));
}
public static WriteConfiguration addPermanentCache(ModifiableConfiguration conf) {
conf.set(DB_CACHE, true);
conf.set(DB_CACHE_TIME,0l);
return conf.getConfiguration();
}
public static ModifiableConfiguration getConfig(WriteConfiguration config) {
return new ModifiableConfiguration(ROOT_NS,config, BasicConfiguration.Restriction.NONE);
}
public static BasicConfiguration getConfig(ReadConfiguration config) {
return new BasicConfiguration(ROOT_NS,config, BasicConfiguration.Restriction.NONE);
}
} | false | titan-test_src_main_java_com_thinkaurelius_titan_StorageSetup.java |
12 | public class TestBed {
static class A {
private int c = 0;
private final Object o;
A(final Object o) {
this.o = o;
}
public void inc() {
c++;
}
}
private static final void doSomethingExpensive(int milliseconds) {
double d=0.0;
Random r = new Random();
for (int i=0;i<10000*milliseconds;i++) d+=Math.pow(1.1,r.nextDouble());
}
/**
* @param args
* @throws java.io.IOException
*/
public static void main(String[] args) throws Exception {
IDHandler.EdgeTypeParse ep = IDHandler.readEdgeType(StaticArrayBuffer.of(new byte[]{36}).asReadBuffer());
System.out.println(ep.typeId + " "+ BaseLabel.VertexLabelEdge.getLongId());
WriteBuffer out = new WriteByteBuffer(20);
IDHandler.writeEdgeType(out, BaseKey.VertexExists.getLongId(),IDHandler.DirectionID.PROPERTY_DIR, BaseKey.VertexExists.isHiddenType());
StaticBuffer b = out.getStaticBuffer();
System.exit(0);
final ScheduledExecutorService exe = new ScheduledThreadPoolExecutor(1,new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
r.run();
}
});
ScheduledFuture future = exe.scheduleWithFixedDelay(new Runnable() {
AtomicInteger atomicInt = new AtomicInteger(0);
@Override
public void run() {
try {
for (int i=0;i<10;i++) {
exe.submit(new Runnable() {
private final int number = atomicInt.incrementAndGet();
@Override
public void run() {
try {
Thread.sleep(150);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(number);
}
});
System.out.println("Submitted: "+i);
// doSomethingExpensive(20);
}
} catch (Exception e) {
e.printStackTrace();
}
}
},0,1, TimeUnit.SECONDS);
Thread.sleep(10000);
// future.get(1,TimeUnit.SECONDS);
System.out.println("Cancel: " + future.cancel(false));
System.out.println("Done: " + future.isDone());
exe.shutdown();
// Thread.sleep(2000);
System.out.println("Terminate: " + exe.awaitTermination(5,TimeUnit.SECONDS));
System.out.println("DONE");
NonBlockingHashMapLong<String> id1 = new NonBlockingHashMapLong<String>(128);
ConcurrentHashMap<Long,String> id2 = new ConcurrentHashMap<Long, String>(128,0.75f,2);
}
public static String toBinary(int b) {
String res = Integer.toBinaryString(b);
while (res.length() < 32) res = "0" + res;
return res;
}
private static void codeSnippets() throws Exception {
TitanGraph g = TitanFactory.open("/tmp/titan");
g.createKeyIndex("name", Vertex.class);
Vertex juno = g.addVertex(null);
juno.setProperty("name", "juno");
juno = g.getVertices("name", "juno").iterator().next();
TransactionalGraph tx = g.newTransaction();
Thread[] threads = new Thread[10];
for (int i = 0; i < threads.length; i++) {
//threads[i]=new Thread(new DoSomething(tx));
threads[i].start();
}
for (int i = 0; i < threads.length; i++) threads[i].join();
tx.commit();
}
} | false | titan-test_src_main_java_com_thinkaurelius_titan_TestBed.java |
13 | final ScheduledExecutorService exe = new ScheduledThreadPoolExecutor(1,new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
r.run();
}
}); | false | titan-test_src_main_java_com_thinkaurelius_titan_TestBed.java |
14 | ScheduledFuture future = exe.scheduleWithFixedDelay(new Runnable() {
AtomicInteger atomicInt = new AtomicInteger(0);
@Override
public void run() {
try {
for (int i=0;i<10;i++) {
exe.submit(new Runnable() {
private final int number = atomicInt.incrementAndGet();
@Override
public void run() {
try {
Thread.sleep(150);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(number);
}
});
System.out.println("Submitted: "+i);
// doSomethingExpensive(20);
}
} catch (Exception e) {
e.printStackTrace();
}
}
},0,1, TimeUnit.SECONDS); | false | titan-test_src_main_java_com_thinkaurelius_titan_TestBed.java |
15 | exe.submit(new Runnable() {
private final int number = atomicInt.incrementAndGet();
@Override
public void run() {
try {
Thread.sleep(150);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(number);
}
}); | false | titan-test_src_main_java_com_thinkaurelius_titan_TestBed.java |
16 | static class A {
private int c = 0;
private final Object o;
A(final Object o) {
this.o = o;
}
public void inc() {
c++;
}
} | false | titan-test_src_main_java_com_thinkaurelius_titan_TestBed.java |
17 | public class TestByteBuffer {
private static final int NUM = 1000;
private static final double FRACTION = 0.2;
private static final int ROUNDSIZE = 5;
private static final int TRIALS = 5;
private static final boolean CHECK_VALUE = true;
private static final Random random = new Random();
public static void main(String[] args) {
SummaryStatistics statObject = new SummaryStatistics();
SummaryStatistics statByte = new SummaryStatistics();
for (int i = 0; i < 10; i++) {
statByte.addValue(testByte());
statObject.addValue(testObject());
}
System.out.println("Time (ms) Object: " + statObject.getMean() + " | " + statObject.getStandardDeviation());
System.out.println("Time (ms) Byte: " + statByte.getMean() + " | " + statByte.getStandardDeviation());
}
private static long testObject() {
EdgeVertex[] vertices = new EdgeVertex[NUM];
for (int i = 0; i < NUM; i++) {
vertices[i] = new EdgeVertex(i);
}
for (int i = 0; i < NUM; i++) {
for (int j = 0; j < NUM; j++) {
if (i == j) continue;
if (Math.random() < FRACTION) {
Edge e = new Edge(vertices[i], "connect", vertices[j]);
e.setProperty("number", random.nextInt(ROUNDSIZE));
vertices[i].addOutEdge(e);
}
}
}
long time = System.currentTimeMillis();
long sum = 0;
for (int t = 0; t < TRIALS; t++) {
for (int i = 0; i < NUM; i++) {
for (Vertex v : vertices[i].getNeighbors(0)) {
sum += v.getId();
}
}
}
time = System.currentTimeMillis() - time;
return time;
}
private static long testByte() {
LongObjectMap<ConcurrentSkipListSet<ByteEntry>> tx = new LongObjectOpenHashMap<ConcurrentSkipListSet<ByteEntry>>(NUM);
for (int i = 0; i < NUM; i++) {
tx.put(i, new ConcurrentSkipListSet<ByteEntry>());
}
for (int i = 0; i < NUM; i++) {
for (int j = 0; j < NUM; j++) {
if (i == j) continue;
if (Math.random() < FRACTION) {
ByteBuffer key = ByteBuffer.allocate(16);
key.putLong(5).putLong(j).flip();
ByteBuffer value = ByteBuffer.allocate(4);
value.putInt(random.nextInt(ROUNDSIZE)).flip();
tx.get(i).add(new ByteEntry(key, value));
}
}
}
long time = System.currentTimeMillis();
long sum = 0;
for (int t = 0; t < TRIALS; t++) {
for (int i = 0; i < NUM; i++) {
for (Vertex v : (new ByteVertex(i, tx)).getNeighbors(0)) {
sum += v.getId();
}
}
}
time = System.currentTimeMillis() - time;
return time;
}
static abstract class Vertex implements Comparable<Vertex> {
protected final long id;
Vertex(long id) {
this.id = id;
}
@Override
public int compareTo(Vertex vertex) {
return Long.valueOf(id).compareTo(vertex.id);
}
public long getId() {
return id;
}
public abstract Iterable<Vertex> getNeighbors(int value);
}
static class EdgeVertex extends Vertex {
private SortedSet<Edge> outEdges = new ConcurrentSkipListSet<Edge>(new Comparator<Edge>() {
@Override
public int compare(Edge e1, Edge e2) {
return e1.getEnd().compareTo(e2.getEnd());
}
});
EdgeVertex(long id) {
super(id);
}
@Override
public Iterable<Vertex> getNeighbors(final int value) {
return Iterables.transform(Iterables.filter(outEdges, new Predicate<Edge>() {
@Override
public boolean apply(@Nullable Edge edge) {
return !CHECK_VALUE || ((Integer) edge.getProperty("number")).intValue() == value;
}
}), new Function<Edge, Vertex>() {
@Override
public Vertex apply(@Nullable Edge edge) {
return edge.getEnd();
}
});
}
void addOutEdge(Edge e) {
outEdges.add(e);
}
}
static class ByteVertex extends Vertex {
private final LongObjectMap<ConcurrentSkipListSet<ByteEntry>> tx;
private final SortedSet<ByteEntry> set;
ByteVertex(long id, LongObjectMap<ConcurrentSkipListSet<ByteEntry>> tx) {
super(id);
this.tx = tx;
this.set = (SortedSet<ByteEntry>) tx.get(id);
}
@Override
public Iterable<Vertex> getNeighbors(final int value) {
// SortedSet<ByteEntry> set = (SortedSet<ByteEntry>) tx.get(id);
return Iterables.transform(Iterables.filter(set, new Predicate<ByteEntry>() {
@Override
public boolean apply(@Nullable ByteEntry entry) {
return !CHECK_VALUE || entry.value.getInt(0) == value;
}
}), new Function<ByteEntry, Vertex>() {
@Override
public Vertex apply(@Nullable ByteEntry entry) {
return new ByteVertex(entry.key.getLong(8), tx);
}
});
}
}
static class Edge {
private final Vertex start;
private final Vertex end;
private final String label;
private final Map<String, Object> properties = new HashMap<String, Object>();
Edge(Vertex start, String label, Vertex end) {
this.label = label;
this.end = end;
this.start = start;
}
public String getLabel() {
return label;
}
void setProperty(String key, Object value) {
properties.put(key, value);
}
public Object getProperty(String key) {
return properties.get(key);
}
public Vertex getStart() {
return start;
}
public Vertex getEnd() {
return end;
}
public Vertex getOther(Vertex v) {
if (start.equals(v)) return end;
else if (end.equals(v)) return start;
throw new IllegalArgumentException();
}
}
static class ByteEntry implements Comparable<ByteEntry> {
final ByteBuffer key;
final ByteBuffer value;
ByteEntry(ByteBuffer key, ByteBuffer value) {
this.value = value;
this.key = key;
}
@Override
public int compareTo(ByteEntry byteEntry) {
return key.compareTo(byteEntry.key);
}
}
} | false | titan-test_src_main_java_com_thinkaurelius_titan_TestByteBuffer.java |
18 | static class ByteEntry implements Comparable<ByteEntry> {
final ByteBuffer key;
final ByteBuffer value;
ByteEntry(ByteBuffer key, ByteBuffer value) {
this.value = value;
this.key = key;
}
@Override
public int compareTo(ByteEntry byteEntry) {
return key.compareTo(byteEntry.key);
}
} | false | titan-test_src_main_java_com_thinkaurelius_titan_TestByteBuffer.java |
19 | static class ByteVertex extends Vertex {
private final LongObjectMap<ConcurrentSkipListSet<ByteEntry>> tx;
private final SortedSet<ByteEntry> set;
ByteVertex(long id, LongObjectMap<ConcurrentSkipListSet<ByteEntry>> tx) {
super(id);
this.tx = tx;
this.set = (SortedSet<ByteEntry>) tx.get(id);
}
@Override
public Iterable<Vertex> getNeighbors(final int value) {
// SortedSet<ByteEntry> set = (SortedSet<ByteEntry>) tx.get(id);
return Iterables.transform(Iterables.filter(set, new Predicate<ByteEntry>() {
@Override
public boolean apply(@Nullable ByteEntry entry) {
return !CHECK_VALUE || entry.value.getInt(0) == value;
}
}), new Function<ByteEntry, Vertex>() {
@Override
public Vertex apply(@Nullable ByteEntry entry) {
return new ByteVertex(entry.key.getLong(8), tx);
}
});
}
} | false | titan-test_src_main_java_com_thinkaurelius_titan_TestByteBuffer.java |
20 | return Iterables.transform(Iterables.filter(set, new Predicate<ByteEntry>() {
@Override
public boolean apply(@Nullable ByteEntry entry) {
return !CHECK_VALUE || entry.value.getInt(0) == value;
}
}), new Function<ByteEntry, Vertex>() { | false | titan-test_src_main_java_com_thinkaurelius_titan_TestByteBuffer.java |
21 | }), new Function<ByteEntry, Vertex>() {
@Override
public Vertex apply(@Nullable ByteEntry entry) {
return new ByteVertex(entry.key.getLong(8), tx);
}
}); | false | titan-test_src_main_java_com_thinkaurelius_titan_TestByteBuffer.java |
22 | static class Edge {
private final Vertex start;
private final Vertex end;
private final String label;
private final Map<String, Object> properties = new HashMap<String, Object>();
Edge(Vertex start, String label, Vertex end) {
this.label = label;
this.end = end;
this.start = start;
}
public String getLabel() {
return label;
}
void setProperty(String key, Object value) {
properties.put(key, value);
}
public Object getProperty(String key) {
return properties.get(key);
}
public Vertex getStart() {
return start;
}
public Vertex getEnd() {
return end;
}
public Vertex getOther(Vertex v) {
if (start.equals(v)) return end;
else if (end.equals(v)) return start;
throw new IllegalArgumentException();
}
} | false | titan-test_src_main_java_com_thinkaurelius_titan_TestByteBuffer.java |
23 | static class EdgeVertex extends Vertex {
private SortedSet<Edge> outEdges = new ConcurrentSkipListSet<Edge>(new Comparator<Edge>() {
@Override
public int compare(Edge e1, Edge e2) {
return e1.getEnd().compareTo(e2.getEnd());
}
});
EdgeVertex(long id) {
super(id);
}
@Override
public Iterable<Vertex> getNeighbors(final int value) {
return Iterables.transform(Iterables.filter(outEdges, new Predicate<Edge>() {
@Override
public boolean apply(@Nullable Edge edge) {
return !CHECK_VALUE || ((Integer) edge.getProperty("number")).intValue() == value;
}
}), new Function<Edge, Vertex>() {
@Override
public Vertex apply(@Nullable Edge edge) {
return edge.getEnd();
}
});
}
void addOutEdge(Edge e) {
outEdges.add(e);
}
} | false | titan-test_src_main_java_com_thinkaurelius_titan_TestByteBuffer.java |
24 | private SortedSet<Edge> outEdges = new ConcurrentSkipListSet<Edge>(new Comparator<Edge>() {
@Override
public int compare(Edge e1, Edge e2) {
return e1.getEnd().compareTo(e2.getEnd());
}
}); | false | titan-test_src_main_java_com_thinkaurelius_titan_TestByteBuffer.java |
25 | return Iterables.transform(Iterables.filter(outEdges, new Predicate<Edge>() {
@Override
public boolean apply(@Nullable Edge edge) {
return !CHECK_VALUE || ((Integer) edge.getProperty("number")).intValue() == value;
}
}), new Function<Edge, Vertex>() { | false | titan-test_src_main_java_com_thinkaurelius_titan_TestByteBuffer.java |
26 | }), new Function<Edge, Vertex>() {
@Override
public Vertex apply(@Nullable Edge edge) {
return edge.getEnd();
}
}); | false | titan-test_src_main_java_com_thinkaurelius_titan_TestByteBuffer.java |
27 | static abstract class Vertex implements Comparable<Vertex> {
protected final long id;
Vertex(long id) {
this.id = id;
}
@Override
public int compareTo(Vertex vertex) {
return Long.valueOf(id).compareTo(vertex.id);
}
public long getId() {
return id;
}
public abstract Iterable<Vertex> getNeighbors(int value);
} | false | titan-test_src_main_java_com_thinkaurelius_titan_TestByteBuffer.java |
28 | public abstract class AbstractCassandraBlueprintsTest extends TitanBlueprintsTest {
@Override
public void beforeSuite() {
//Do nothing
}
@Override
public TitanGraph openGraph(String uid) {
return TitanFactory.open(getGraphConfig());
}
@Override
public boolean supportsMultipleGraphs() {
return false;
}
protected abstract WriteConfiguration getGraphConfig();
} | false | titan-cassandra_src_test_java_com_thinkaurelius_titan_blueprints_AbstractCassandraBlueprintsTest.java |
29 | public class BerkeleyBlueprintsTest extends TitanBlueprintsTest {
private static final String DEFAULT_SUBDIR = "standard";
private static final Logger log =
LoggerFactory.getLogger(BerkeleyBlueprintsTest.class);
@Override
public Graph generateGraph() {
return generateGraph(DEFAULT_SUBDIR);
}
@Override
public void beforeOpeningGraph(String uid) {
String dir = BerkeleyStorageSetup.getHomeDir(uid);
log.debug("Cleaning directory {} before opening it for the first time", dir);
try {
BerkeleyJEStoreManager s = new BerkeleyJEStoreManager(BerkeleyStorageSetup.getBerkeleyJEConfiguration(dir));
s.clearStorage();
s.close();
File dirFile = new File(dir);
Assert.assertFalse(dirFile.exists() && dirFile.listFiles().length > 0);
} catch (BackendException e) {
throw new RuntimeException(e);
}
}
@Override
public TitanGraph openGraph(String uid) {
String dir = BerkeleyStorageSetup.getHomeDir(uid);
return TitanFactory.open(BerkeleyStorageSetup.getBerkeleyJEConfiguration(dir));
}
@Override
public void extraCleanUp(String uid) throws BackendException {
String dir = BerkeleyStorageSetup.getHomeDir(uid);
BerkeleyJEStoreManager s = new BerkeleyJEStoreManager(BerkeleyStorageSetup.getBerkeleyJEConfiguration(dir));
s.clearStorage();
s.close();
File dirFile = new File(dir);
Assert.assertFalse(dirFile.exists() && dirFile.listFiles().length > 0);
}
@Override
public boolean supportsMultipleGraphs() {
return true;
}
@Override
public void beforeSuite() {
//Nothing
}
@Override
public void afterSuite() {
synchronized (openGraphs) {
for (String dir : openGraphs.keySet()) {
File dirFile = new File(dir);
Assert.assertFalse(dirFile.exists() && dirFile.listFiles().length > 0);
}
}
}
} | false | titan-berkeleyje_src_test_java_com_thinkaurelius_titan_blueprints_BerkeleyBlueprintsTest.java |
30 | public class EmbeddedBlueprintsTest extends AbstractCassandraBlueprintsTest {
@Override
protected WriteConfiguration getGraphConfig() {
return CassandraStorageSetup.getEmbeddedGraphConfiguration(getClass().getSimpleName());
}
@Override
public void extraCleanUp(String uid) throws BackendException {
ModifiableConfiguration mc =
new ModifiableConfiguration(GraphDatabaseConfiguration.ROOT_NS, getGraphConfig(), Restriction.NONE);
StoreManager m = new CassandraEmbeddedStoreManager(mc);
m.clearStorage();
m.close();
}
} | false | titan-cassandra_src_test_java_com_thinkaurelius_titan_blueprints_EmbeddedBlueprintsTest.java |
31 | public class HBaseBlueprintsTest extends TitanBlueprintsTest {
@Override
public void beforeSuite() {
try {
HBaseStorageSetup.startHBase();
} catch (IOException e) {
throw new AssertionError(e);
}
}
@AfterClass
public static void stopHBase() {
// Workaround for https://issues.apache.org/jira/browse/HBASE-10312
if (VersionInfo.getVersion().startsWith("0.96"))
HBaseStorageSetup.killIfRunning();
}
@Override
public void extraCleanUp(String uid) throws BackendException {
HBaseStoreManager s = new HBaseStoreManager(HBaseStorageSetup.getHBaseConfiguration());
s.clearStorage();
s.close();
}
@Override
public boolean supportsMultipleGraphs() {
return false;
}
@Override
protected TitanGraph openGraph(String uid) {
return TitanFactory.open(HBaseStorageSetup.getHBaseGraphConfiguration());
}
} | false | titan-hbase-parent_titan-hbase-core_src_test_java_com_thinkaurelius_titan_blueprints_HBaseBlueprintsTest.java |
32 | public abstract class InMemoryBlueprintsTest extends TitanBlueprintsTest {
public void testGraphTestSuite() throws Exception {
this.stopWatch();
doTestSuite(new GraphTestSuite(this), ImmutableSet.of("testStringRepresentation","testDataTypeValidationOnProperties","testGraphDataPersists"));
BaseTest.printTestPerformance("GraphTestSuite", this.stopWatch());
}
///=========================== DEFAULT ===========
@Override
public void cleanUp() throws BackendException {
}
@Override
public boolean supportsMultipleGraphs() {
return false;
}
@Override
public void beforeSuite() {
}
@Override
public void afterSuite() {
}
@Override
public Graph generateGraph() {
TitanGraph graph = StorageSetup.getInMemoryGraph();
return graph;
}
@Override
public Graph generateGraph(String graphDirectoryName) {
throw new UnsupportedOperationException();
}
} | false | titan-test_src_test_java_com_thinkaurelius_titan_blueprints_InMemoryBlueprintsTest.java |
33 | public class ThriftBlueprintsTest extends AbstractCassandraBlueprintsTest {
@Override
public void beforeSuite() {
CassandraStorageSetup.startCleanEmbedded();
}
@Override
protected WriteConfiguration getGraphConfig() {
return CassandraStorageSetup.getCassandraGraphConfiguration(getClass().getSimpleName());
}
@Override
public void extraCleanUp(String uid) throws BackendException {
ModifiableConfiguration mc =
new ModifiableConfiguration(GraphDatabaseConfiguration.ROOT_NS, getGraphConfig(), Restriction.NONE);
StoreManager m = new CassandraThriftStoreManager(mc);
m.clearStorage();
m.close();
}
} | false | titan-cassandra_src_test_java_com_thinkaurelius_titan_blueprints_ThriftBlueprintsTest.java |
34 | public abstract class TitanBlueprintsTest extends GraphTest {
private static final Logger log =
LoggerFactory.getLogger(TitanBlueprintsTest.class);
private volatile String lastSeenMethodName;
protected final Map<String, TitanGraph> openGraphs = new HashMap<String, TitanGraph>();
public void testVertexTestSuite() throws Exception {
this.stopWatch();
doTestSuite(new VertexTestSuite(this));
printTestPerformance("VertexTestSuite", this.stopWatch());
}
public void testVertexQueryTestSuite() throws Exception {
this.stopWatch();
doTestSuite(new VertexQueryTestSuite(this));
printTestPerformance("VertexQueryTestSuite", this.stopWatch());
}
public void testEdgeTestSuite() throws Exception {
this.stopWatch();
doTestSuite(new TitanEdgeTestSuite(this), ImmutableSet.of("testEdgeIterator")); //had to be removed due to a bug in the test TODO: re-add with next blueprints release
printTestPerformance("EdgeTestSuite", this.stopWatch());
}
public void testGraphTestSuite() throws Exception {
this.stopWatch();
//Excluded "testStringRepresentation" test case because toString representation is non-standard
//Excluded "testConnectivityPatterns","testTreeConnectivity","testGraphDataPersists" because of bug in test. TODO: re-add with next blueprints release
doTestSuite(new GraphTestSuite(this), ImmutableSet.of("testStringRepresentation",
"testConnectivityPatterns","testTreeConnectivity","testGraphDataPersists"));
printTestPerformance("GraphTestSuite", this.stopWatch());
}
public void testGraphQueryTestSuite() throws Exception {
this.stopWatch();
doTestSuite(new TitanGraphQueryTestSuite(this));
printTestPerformance("GraphQueryTestSuite", this.stopWatch());
}
public void testTransactionalGraphTestSuite() throws Exception {
this.stopWatch();
Set<String> excludedTests = new HashSet<String>();
if (!supportsMultipleGraphs()) excludedTests.add("testCompetingThreadsOnMultipleDbInstances");
doTestSuite(new TransactionalTitanGraphTestSuite(this), excludedTests);
printTestPerformance("TransactionalTitanGraphTestSuite", this.stopWatch());
}
public void testTitanSpecificTestSuite() throws Exception {
this.stopWatch();
doTestSuite(new TitanSpecificBlueprintsTestSuite(this));
printTestPerformance("TitanSpecificBlueprintsTestSuite", this.stopWatch());
}
public void testGraphMLReaderTestSuite() throws Exception {
this.stopWatch();
doTestSuite(new GraphMLReaderTestSuite(this));
printTestPerformance("GraphMLReaderTestSuite", this.stopWatch());
}
public void testGraphSONReaderTestSuite() throws Exception {
this.stopWatch();
doTestSuite(new GraphSONReaderTestSuite(this));
printTestPerformance("GraphSONReaderTestSuite", this.stopWatch());
}
public void testGMLReaderTestSuite() throws Exception {
this.stopWatch();
doTestSuite(new GMLReaderTestSuite(this));
printTestPerformance("GMLReaderTestSuite", this.stopWatch());
}
/**
*
* @return true, if {@link #generateGraph(String)} is supported
*/
public abstract boolean supportsMultipleGraphs();
//public abstract void cleanUp() throws BackendException;
public abstract void beforeSuite();
public void afterSuite() {
// Most impls do nothing by default
}
protected String getMostRecentMethodName() {
return lastSeenMethodName;
}
@Override
public Object convertId(final Object id) {
return null;
}
@Override
public String convertLabel(String label) {
return label;
}
@Override
public void doTestSuite(TestSuite testSuite) throws Exception {
doTestSuite(testSuite, new HashSet<String>());
}
protected abstract TitanGraph openGraph(String uid);
protected void beforeOpeningGraph(String uid) {
log.debug("Opening graph[uid={}] for the first time", uid);
}
protected void extraCleanUp(String uid) throws BackendException {
}
@Override
public Graph generateGraph() {
return generateGraph("_DEFAULT_TITAN_GRAPH_UID");
}
@Override
public Graph generateGraph(String uid) {
synchronized (openGraphs) {
if (!openGraphs.containsKey(uid)) {
beforeOpeningGraph(uid);
} else if (openGraphs.get(uid).isOpen()) {
log.warn("Detected possible graph[uid={}] leak in Blueprints GraphTest method {}, shutting down the leaked graph",
uid, getMostRecentMethodName());
openGraphs.get(uid).shutdown();
} else {
log.debug("Reopening previously-closed graph[uid={}]", uid);
}
}
log.info("Opening graph with uid={}", uid);
openGraphs.put(uid, openGraph(uid));
return openGraphs.get(uid);
}
public void cleanUp() throws BackendException {
synchronized (openGraphs) {
for (Map.Entry<String, TitanGraph> entry : openGraphs.entrySet()) {
String uid = entry.getKey();
TitanGraph g = entry.getValue();
if (g.isOpen()) {
log.warn("Detected possible graph[uid={}] leak in Blueprints GraphTest method {}, shutting down the leaked graph",
uid, getMostRecentMethodName());
g.shutdown();
}
extraCleanUp(uid);
}
openGraphs.clear();
}
}
public void doTestSuite(TestSuite testSuite, Set<String> ignoreTests) throws Exception {
beforeSuite();
cleanUp();
for (Method method : testSuite.getClass().getMethods()) {
if (ignoreTests.contains(method.getName())
|| !method.getName().startsWith("test")) continue;
String name = testSuite.getClass().getSimpleName() + "." + method.getName();
lastSeenMethodName = name;
try {
log.info("Testing " + name + "...");
method.invoke(testSuite);
// System.out.println("##################### MEMORY ############");
// System.out.println(MemoryAssess.getMemoryUse()/1024);
// graph = null;
} catch (Throwable e) {
log.error("Encountered error in " + name);
e.printStackTrace();
throw new RuntimeException(e);
} finally {
cleanUp();
}
}
afterSuite();
}
} | false | titan-test_src_main_java_com_thinkaurelius_titan_blueprints_TitanBlueprintsTest.java |
35 | public class TitanEdgeTestSuite extends EdgeTestSuite {
public TitanEdgeTestSuite(final GraphTest graphTest) {
super(graphTest);
}
} | false | titan-test_src_main_java_com_thinkaurelius_titan_blueprints_TitanEdgeTestSuite.java |
36 | public class TitanGraphQueryTestSuite extends GraphQueryTestSuite {
public TitanGraphQueryTestSuite(final GraphTest graphTest) {
super(graphTest);
}
@Override
public void testGraphQueryForVertices() {
TitanGraph g = (TitanGraph) graphTest.generateGraph();
if (g.getRelationType("age") == null) {
TitanManagement mgmt = g.getManagementSystem();
mgmt.makePropertyKey("age").dataType(Integer.class).cardinality(Cardinality.SINGLE).make();
mgmt.commit();
}
g.shutdown();
super.testGraphQueryForVertices();
}
@Override
public void testGraphQueryForEdges() {
TitanGraph g = (TitanGraph) graphTest.generateGraph();
if (g.getRelationType("weight") == null) {
TitanManagement mgmt = g.getManagementSystem();
mgmt.makePropertyKey("weight").dataType(Double.class).cardinality(Cardinality.SINGLE).make();
mgmt.commit();
}
g.shutdown();
super.testGraphQueryForEdges();
}
} | false | titan-test_src_main_java_com_thinkaurelius_titan_blueprints_TitanGraphQueryTestSuite.java |
37 | public class TitanSpecificBlueprintsTestSuite extends TestSuite {
public TitanSpecificBlueprintsTestSuite(final GraphTest graphTest) {
super(graphTest);
}
public void testVertexReattachment() {
TransactionalGraph graph = (TransactionalGraph) graphTest.generateGraph();
Vertex a = graph.addVertex(null);
Vertex b = graph.addVertex(null);
Edge e = graph.addEdge(null, a, b, "friend");
graph.commit();
a = graph.getVertex(a);
Assert.assertNotNull(a);
Assert.assertEquals(1, BaseTest.count(a.getVertices(Direction.OUT)));
graph.shutdown();
}
} | false | titan-test_src_main_java_com_thinkaurelius_titan_blueprints_TitanSpecificBlueprintsTestSuite.java |
38 | public class TransactionalTitanGraphTestSuite extends TransactionalGraphTestSuite {
public TransactionalTitanGraphTestSuite(final GraphTest graphTest) {
super(graphTest);
}
@Override
public void testCompetingThreads() {
TitanBlueprintsGraph graph = (TitanBlueprintsGraph) graphTest.generateGraph();
//Need to define types before hand to avoid deadlock in transactions
TitanManagement mgmt = graph.getManagementSystem();
mgmt.makeEdgeLabel("friend").make();
mgmt.makePropertyKey("test").dataType(Long.class).make();
mgmt.makePropertyKey("blah").dataType(Float.class).make();
mgmt.makePropertyKey("bloop").dataType(Integer.class).make();
mgmt.commit();
graph.shutdown();
super.testCompetingThreads();
}
} | false | titan-test_src_main_java_com_thinkaurelius_titan_blueprints_TransactionalTitanGraphTestSuite.java |
39 | public interface BaseVertexQuery<Q extends BaseVertexQuery<Q>> {
/* ---------------------------------------------------------------
* Query Specification
* ---------------------------------------------------------------
*/
/**
* Restricts this query to only those edges that point to the given vertex.
*
* @param vertex
* @return this query builder
*/
public Q adjacent(TitanVertex vertex);
/**
* Query for only those relations matching one of the given relation types.
* By default, a query includes all relations in the result set.
*
* @param type relation types to query for
* @return this query
*/
public Q types(RelationType... type);
/**
* Query for only those edges matching one of the given edge labels.
* By default, an edge query includes all edges in the result set.
*
* @param labels edge labels to query for
* @return this query
*/
public Q labels(String... labels);
/**
* Query for only those properties having one of the given property keys.
* By default, a query includes all properties in the result set.
*
* @param keys property keys to query for
* @return this query
*/
public Q keys(String... keys);
/**
* Query only for relations in the given direction.
* By default, both directions are queried.
*
* @param d Direction to query for
* @return this query
*/
public Q direction(Direction d);
/**
* Query only for edges or properties that have an incident property matching the given value.
* <p/>
*
* @param key key
* @param value Value for the property of the given key to match
* @return this query
*/
public Q has(PropertyKey key, Object value);
/**
* Query only for edges or properties that have a unidirected edge pointing to the given vertex
* <p/>
* It is expected that this label is unidirected ({@link EdgeLabel#isUnidirected()}
* and the query is restricted to edges or properties having an incident unidirectional edge pointing to the given vertex.
*
* @param label Label
* @param vertex Vertex to point unidirectional edge to
* @return this query
*/
public Q has(EdgeLabel label, TitanVertex vertex);
/**
* Query for edges or properties that have defined property with the given key
*
* @param key
* @return this query
*/
public Q has(String key);
/**
* Query for edges or properties that DO NOT have a defined property with the given key
*
* @param key
* @return this query
*/
public Q hasNot(String key);
/**
* Query only for edges or properties that have an incident property or unidirected edge matching the given value.
* <p/>
* If type is a property key, then the query is restricted to edges or properties having an incident property matching
* this key-value pair.
* If type is an edge label, then it is expected that this label is unidirected ({@link EdgeLabel#isUnidirected()}
* and the query is restricted to edges or properties having an incident unidirectional edge pointing to the value which is
* expected to be a {@link com.thinkaurelius.titan.core.TitanVertex}.
*
* @param type TitanType name
* @param value Value for the property of the given key to match, or vertex to point unidirectional edge to
* @return this query
*/
public Q has(String type, Object value);
/**
* Identical to {@link #has(String, Object)} but negates the condition, i.e. matches those edges or properties
* that DO NOT satisfy this property condition.
*
* @param key
* @param value
* @return
*/
public Q hasNot(String key, Object value);
/**
* Query only for those edges or properties which have a property for the given key that satisfies the specified
* predicate relationship to the provided value.
*
* @param key property key
* @param predicate boolean relationship to satisfy with the given value
* @param value value
* @return
*/
public Q has(PropertyKey key, Predicate predicate, Object value);
/**
* Query only for those edges or properties which have a property for the given key that satisfies the specified
* predicate relationship to the provided value.
*
* @param key property key
* @param predicate boolean relationship to satisfy with the given value
* @param value value
* @return
*/
public Q has(String key, Predicate predicate, Object value);
/**
* Query for those edges or properties that have a property for the given key
* whose values lies in the interval by [start,end).
*
* @param key property key
* @param start value defining the start of the interval (inclusive)
* @param end value defining the end of the interval (exclusive)
* @return this query
*/
public <T extends Comparable<?>> Q interval(String key, T start, T end);
/**
* Query for those edges or properties that have a property for the given key
* whose values lies in the interval by [start,end).
*
* @param key property key
* @param start value defining the start of the interval (inclusive)
* @param end value defining the end of the interval (exclusive)
* @return this query
*/
public <T extends Comparable<?>> Q interval(PropertyKey key, T start, T end);
/**
* Sets the retrieval limit for this query.
* <p/>
* When setting a limit, executing this query will only retrieve the specified number of relations. Note, that this
* also applies to counts.
*
* @param limit maximum number of relations to retrieve for this query
* @return this query
*/
public Q limit(int limit);
/**
* Orders the relation results of this query according
* to their property for the given key in the given order (increasing/decreasing).
* </p>
* Note, that the ordering always applies to the incident relations (edges/properties) and NOT
* to the adjacent vertices even if only vertices are being returned.
*
* @param key The key of the properties on which to order
* @param order the ordering direction
* @return
*/
public Q orderBy(String key, Order order);
/**
* Orders the relation results of this query according
* to their property for the given key in the given order (increasing/decreasing).
* </p>
* Note, that the ordering always applies to the incident relations (edges/properties) and NOT
* to the adjacent vertices even if only vertices are being returned.
*
* @param key The key of the properties on which to order
* @param order the ordering direction
* @return
*/
public Q orderBy(PropertyKey key, Order order);
/* ---------------------------------------------------------------
* Query Execution
* ---------------------------------------------------------------
*/
/**
* Returns a description of this query for edges as a {@link QueryDescription} object.
*
* This can be used to inspect the query plan for this query. Note, that calling this method
* does not actually execute the query but only optimizes it and constructs a query plan.
*
* @return A description of this query for edges
*/
public QueryDescription describeForEdges();
/**
* Returns a description of this query for properties as a {@link QueryDescription} object.
*
* This can be used to inspect the query plan for this query. Note, that calling this method
* does not actually execute the query but only optimizes it and constructs a query plan.
*
* @return A description of this query for properties
*/
public QueryDescription describeForProperties();
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_BaseVertexQuery.java |
40 | public enum Cardinality {
/**
* Only a single value may be associated with the given key.
*/
SINGLE,
/**
* Multiple values and duplicate values may be associated with the given key.
*/
LIST,
/**
* Multiple but distinct values may be associated with the given key.
*/
SET;
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_Cardinality.java |
41 | public interface EdgeLabel extends RelationType {
/**
* Checks whether this labels is defined as directed.
*
* @return true, if this label is directed, else false.
*/
public boolean isDirected();
/**
* Checks whether this labels is defined as unidirected.
*
* @return true, if this label is unidirected, else false.
*/
public boolean isUnidirected();
/**
* The {@link Multiplicity} for this edge label.
*
* @return
*/
public Multiplicity getMultiplicity();
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_EdgeLabel.java |
42 | public interface Idfiable {
/**
* Unique identifier for this entity.
*
* @return Unique long id for this entity
*/
public long getLongId();
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_Idfiable.java |
43 | public class InvalidElementException extends TitanException {
private final TitanElement element;
/**
* @param msg Exception message
* @param element The invalid element causing the exception
*/
public InvalidElementException(String msg, TitanElement element) {
super(msg);
this.element = element;
}
/**
* Returns the element causing the exception
*
* @return The element causing the exception
*/
public TitanElement getElement() {
return element;
}
@Override
public String toString() {
return super.toString() + " [" + element.toString() + "]";
}
public static IllegalStateException removedException(TitanElement element) {
return new IllegalStateException("Element has been removed");
}
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_InvalidElementException.java |
44 | public class InvalidIDException extends TitanException {
public InvalidIDException(String msg) {
super(msg);
}
public InvalidIDException(String msg, Throwable cause) {
super(msg, cause);
}
public InvalidIDException(Throwable cause) {
super(cause);
}
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_InvalidIDException.java |
45 | public enum Multiplicity {
/**
* The given edge label specifies a multi-graph, meaning that the multiplicity is not constrained and that
* there may be multiple edges of this label between any given pair of vertices.
*
* @link http://en.wikipedia.org/wiki/Multigraph
*/
MULTI,
/**
* The given edge label specifies a simple graph, meaning that the multiplicity is not constrained but that there
* can only be at most a single edge of this label between a given pair of vertices.
*/
SIMPLE,
/**
* There can only be a single in-edge of this label for a given vertex but multiple out-edges (i.e. in-unique)
*/
ONE2MANY,
/**
* There can only be a single out-edge of this label for a given vertex but multiple in-edges (i.e. out-unique)
*/
MANY2ONE,
/**
* There can be only a single in and out-edge of this label for a given vertex (i.e. unique in both directions).
*/
ONE2ONE;
/**
* Whether this multiplicity imposes any constraint on the number of edges that may exist between a pair of vertices.
*
* @return
*/
public boolean isConstrained() {
return this!=MULTI;
}
public boolean isConstrained(Direction direction) {
if (direction==Direction.BOTH) return isConstrained();
if (this==MULTI) return false;
if (this==SIMPLE) return true;
return isUnique(direction);
}
/**
* If this multiplicity implies edge uniqueness in the given direction for any given vertex.
*
* @param direction
* @return
*/
public boolean isUnique(Direction direction) {
switch (direction) {
case IN:
return this==ONE2MANY || this==ONE2ONE;
case OUT:
return this==MANY2ONE || this==ONE2ONE;
case BOTH:
return this==ONE2ONE;
default: throw new AssertionError("Unknown direction: " + direction);
}
}
//######### CONVERTING MULTIPLICITY <-> CARDINALITY ########
public static Multiplicity convert(Cardinality cardinality) {
Preconditions.checkNotNull(cardinality);
switch(cardinality) {
case LIST: return MULTI;
case SET: return SIMPLE;
case SINGLE: return MANY2ONE;
default: throw new AssertionError("Unknown cardinality: " + cardinality);
}
}
public Cardinality getCardinality() {
switch (this) {
case MULTI: return Cardinality.LIST;
case SIMPLE: return Cardinality.SET;
case MANY2ONE: return Cardinality.SINGLE;
default: throw new AssertionError("Invalid multiplicity: " + this);
}
}
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_Multiplicity.java |
46 | public interface Namifiable {
/**
* Returns the unique name of this entity.
*
* @return Name of this entity.
*/
public String getName();
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_Namifiable.java |
47 | public enum Order {
/**
* Increasing
*/
ASC,
/**
* Decreasing
*/
DESC;
/**
* Modulates the result of a {@link Comparable#compareTo(Object)} execution for this specific
* order, i.e. it negates the result if the order is {@link #DESC}.
*
* @param compare
* @return
*/
public int modulateNaturalOrder(int compare) {
switch (this) {
case ASC:
return compare;
case DESC:
return -compare;
default:
throw new AssertionError("Unrecognized order: " + this);
}
}
/**
* The default order when none is specified
*/
public static final Order DEFAULT = ASC;
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_Order.java |
48 | public interface PropertyKey extends RelationType {
/**
* Returns the data type for this property key.
* The values of all properties of this type must be an instance of this data type.
*
* @return Data type for this property key.
*/
public Class<?> getDataType();
/**
* The {@link Cardinality} of this property key.
* @return
*/
public Cardinality getCardinality();
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_PropertyKey.java |
49 | public interface QueryDescription {
/**
* Returns a string representation of the entire query
* @return
*/
@Override
public String toString();
/**
* Returns how many individual queries are combined into this query, meaning, how many
* queries will be executed in one batch.
*
* @return
*/
public int getNoCombinedQueries();
/**
* Returns the number of sub-queries this query is comprised of. Each sub-query represents one OR clause, i.e.,
* the union of each sub-query's result is the overall result.
*
* @return
*/
public int getNoSubQueries();
/**
* Returns a list of all sub-queries that comprise this query
* @return
*/
public List<? extends SubQuery> getSubQueries();
/**
* Represents one sub-query of this query. Each sub-query represents one OR clause.
*/
public interface SubQuery {
/**
* Whether this query is fitted, i.e. whether the returned results must be filtered in-memory.
* @return
*/
public boolean isFitted();
/**
* Whether this query respects the sort order of parent query or requires sorting in-memory.
* @return
*/
public boolean isSorted();
}
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_QueryDescription.java |
50 | public interface SubQuery {
/**
* Whether this query is fitted, i.e. whether the returned results must be filtered in-memory.
* @return
*/
public boolean isFitted();
/**
* Whether this query respects the sort order of parent query or requires sorting in-memory.
* @return
*/
public boolean isSorted();
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_QueryDescription.java |
51 | public class QueryException extends TitanException {
private static final long serialVersionUID = 1L;
/**
* @param msg Exception message
*/
public QueryException(String msg) {
super(msg);
}
/**
* @param msg Exception message
* @param cause Cause of the exception
*/
public QueryException(String msg, Throwable cause) {
super(msg, cause);
}
/**
* Constructs an exception with a generic message
*
* @param cause Cause of the exception
*/
public QueryException(Throwable cause) {
this("Exception in query.", cause);
}
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_QueryException.java |
52 | public interface RelationType extends TitanVertex, TitanSchemaType {
/**
* Checks if this relation type is a property key
*
* @return true, if this relation type is a property key, else false.
* @see PropertyKey
*/
public boolean isPropertyKey();
/**
* Checks if this relation type is an edge label
*
* @return true, if this relation type is a edge label, else false.
* @see EdgeLabel
*/
public boolean isEdgeLabel();
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_RelationType.java |
53 | public class SchemaViolationException extends TitanException {
public SchemaViolationException(String msg) {
super(msg);
}
public SchemaViolationException(String msg, Object... args) {
super(String.format(msg,args));
}
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_SchemaViolationException.java |
54 | public class Titan {
/**
* The version of this Titan graph database
*
* @return
*/
public static String version() {
return TitanConstants.VERSION;
}
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_Titan.java |
55 | public class TitanConfigurationException extends TitanException {
private static final long serialVersionUID = 4056436257763972423L;
/**
* @param msg Exception message
*/
public TitanConfigurationException(String msg) {
super(msg);
}
/**
* @param msg Exception message
* @param cause Cause of the exception
*/
public TitanConfigurationException(String msg, Throwable cause) {
super(msg, cause);
}
/**
* Constructs an exception with a generic message
*
* @param cause Cause of the exception
*/
public TitanConfigurationException(Throwable cause) {
this("Exception in graph database configuration", cause);
}
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_TitanConfigurationException.java |
56 | public interface TitanEdge extends TitanRelation, Edge {
/**
* Returns the edge label of this edge
*
* @return edge label of this edge
*/
public EdgeLabel getEdgeLabel();
/**
* Returns the vertex for the specified direction.
* The direction cannot be Direction.BOTH.
*
* @return the vertex for the specified direction
*/
public TitanVertex getVertex(Direction dir);
/**
* Returns the vertex at the opposite end of the edge.
*
* @param vertex vertex on which this edge is incident
* @return The vertex at the opposite end of the edge.
* @throws InvalidElementException if the edge is not incident on the specified vertex
*/
public TitanVertex getOtherVertex(TitanVertex vertex);
/**
* Checks whether this relation is directed, i.e. has a start and end vertex
* both of which are aware of the incident edge.
*
* @return true, if this relation is directed, else false.
*/
public boolean isDirected();
/**
* Checks whether this relation is unidirected, i.e. only the start vertex is aware of
* the edge's existence. A unidirected edge is similar to a link.
*
* @return true, if this relation is unidirected, else false.
*/
public boolean isUnidirected();
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_TitanEdge.java |
57 | public interface TitanElement extends Element, Idfiable, Removable {
/**
* Returns a unique identifier for this entity.
* <p/>
* The unique identifier may only be set when the transaction in which entity is created commits.
* The <a href="https://github.com/thinkaurelius/titan/wiki/Graph-Configuration">Graph Configuration Wiki</a> explains
* how to configure when entity ids are assigned.
* Some entities are never assigned a unique identifier if they depend on a parent entity.
* <p/>
*
* @return The unique identifier for this entity
* @throws IllegalStateException if the entity does not (yet) have a unique identifier
* @see #hasId
*/
public Object getId();
/**
* Unique identifier for this entity. This id can be temporarily assigned and might change.
* Use {@link #getId()} for the permanent id.
*
* @return Unique long id
*/
public long getLongId();
/**
* Checks whether this entity has a unique identifier.
* <p/>
* Note that some entities may never be assigned an identifier and others will only be
* assigned an identifier at the end of a transaction.
*
* @return true if this entity has been assigned a unique id, else false
* @see #getLongId()
*/
public boolean hasId();
/**
* Deletes this entity and any incident edges or properties from the graph.
* <p/>
*
* @throws IllegalStateException if the entity cannot be deleted or if the user does not
* have permission to remove the entity
*/
public void remove();
/**
* Sets the value for the given key on this element.
* The key must be defined to have {@link Cardinality#SINGLE}, otherwise this method throws an exception.
*
* @param key the string identifying the key
* @param value the object value
*/
public void setProperty(String key, Object value);
/**
* Sets the value for the given key on this element.
* The key must be defined to have {@link Cardinality#SINGLE}, otherwise this method throws an exception.
*
* @param key the key
* @param value the object value
*/
public void setProperty(PropertyKey key, Object value);
/**
* Retrieves the value associated with the given key on this vertex and casts it to the specified type.
* If the key has cardinality SINGLE, then there can be at most one value and this value is returned (or null).
* Otherwise a list of all associated values is returned, or an empty list if non exist.
* <p/>
*
* @param key key
* @return value or list of values associated with key
*/
public <O> O getProperty(PropertyKey key);
/**
* Retrieves the value associated with the given key on this vertex and casts it to the specified type.
* If the key has cardinality SINGLE, then there can be at most one value and this value is returned (or null).
* Otherwise a list of all associated values is returned, or an empty list if non exist.
* <p/>
*
* @param key string identifying a key
* @return value or list of values associated with key
*/
public <O> O getProperty(String key);
/**
* Removes the value associated with the given key for this vertex (if exists).
*
* @param key the string identifying the key
* @return the object value associated with that key prior to removal, or NULL if such does not exist.
* @see #removeProperty(RelationType)
*/
public <O> O removeProperty(String key);
/**
* Removes the value associated with the given key for this vertex (if exists).
* If the key is list-valued then all values associated with this key are removed and only
* the last removed value returned.
*
* @param type the key
* @return the object value associated with that key prior to removal, or NULL if such does not exist.
*/
public <O> O removeProperty(RelationType type);
//########### LifeCycle Status ##########
/**
* Checks whether this entity has been newly created in the current transaction.
*
* @return True, if entity has been newly created, else false.
*/
public boolean isNew();
/**
* Checks whether this entity has been loaded into the current transaction and not yet modified.
*
* @return True, has been loaded and not modified, else false.
*/
public boolean isLoaded();
/**
* Checks whether this entity has been deleted into the current transaction.
*
* @return True, has been deleted, else false.
*/
public boolean isRemoved();
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_TitanElement.java |
58 | public class TitanException extends RuntimeException {
private static final long serialVersionUID = 4056436257763972423L;
/**
* @param msg Exception message
*/
public TitanException(String msg) {
super(msg);
}
/**
* @param msg Exception message
* @param cause Cause of the exception
*/
public TitanException(String msg, Throwable cause) {
super(msg, cause);
}
/**
* Constructs an exception with a generic message
*
* @param cause Cause of the exception
*/
public TitanException(Throwable cause) {
this("Exception in Titan", cause);
}
/**
* Checks whether this exception is cause by an exception of the given type.
*
* @param causeExceptionType exception type
* @return true, if this exception is caused by the given type
*/
public boolean isCausedBy(Class<?> causeExceptionType) {
return ExceptionUtil.isCausedBy(this, causeExceptionType);
}
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_TitanException.java |
59 | public class TitanFactory {
private static final Logger log =
LoggerFactory.getLogger(TitanFactory.class);
/**
* Opens a {@link TitanGraph} database.
* <p/>
* If the argument points to a configuration file, the configuration file is loaded to configure the Titan graph
* If the string argument is a configuration short-cut, then the short-cut is parsed and used to configure the returned Titan graph.
* <p />
* A configuration short-cut is of the form:
* [STORAGE_BACKEND_NAME]:[DIRECTORY_OR_HOST]
*
* @param shortcutOrFile Configuration file name or configuration short-cut
* @return Titan graph database configured according to the provided configuration
* @see <a href="https://github.com/thinkaurelius/titan/wiki/Graph-Configuration">Graph Configuration Wiki</a>
*/
public static TitanGraph open(String shortcutOrFile) {
return open(getLocalConfiguration(shortcutOrFile));
}
/**
* Opens a {@link TitanGraph} database configured according to the provided configuration.
*
* @param configuration Configuration for the graph database
* @return Titan graph database
* @see <a href="https://github.com/thinkaurelius/titan/wiki/Graph-Configuration">Graph Configuration Wiki</a>
*/
public static TitanGraph open(Configuration configuration) {
return open(new CommonsConfiguration(configuration));
}
/**
* Opens a {@link TitanGraph} database configured according to the provided configuration.
*
* @param configuration Configuration for the graph database
* @return Titan graph database
*/
public static TitanGraph open(BasicConfiguration configuration) {
return open(configuration.getConfiguration());
}
/**
* Opens a {@link TitanGraph} database configured according to the provided configuration.
*
* @param configuration Configuration for the graph database
* @return Titan graph database
*/
public static TitanGraph open(ReadConfiguration configuration) {
return new StandardTitanGraph(new GraphDatabaseConfiguration(configuration));
}
/**
* Returns a {@link Builder} that allows to set the configuration options for opening a Titan graph database.
* <p />
* In the builder, the configuration options for the graph can be set individually. Once all options are configured,
* the graph can be opened with {@link com.thinkaurelius.titan.core.TitanFactory.Builder#open()}.
*
* @return
*/
public static Builder build() {
return new Builder();
}
//--------------------- BUILDER -------------------------------------------
public static class Builder extends UserModifiableConfiguration {
private Builder() {
super(GraphDatabaseConfiguration.buildConfiguration());
}
/**
* Configures the provided configuration path to the given value.
*
* @param path
* @param value
* @return
*/
public Builder set(String path, Object value) {
super.set(path, value);
return this;
}
/**
* Opens a Titan graph with the previously configured options.
*
* @return
*/
public TitanGraph open() {
return TitanFactory.open(super.getConfiguration());
}
}
/**
* Returns a {@link com.thinkaurelius.titan.core.log.LogProcessorFramework} for processing transaction log entries
* against the provided graph instance.
*
* @param graph
* @return
*/
public static LogProcessorFramework openTransactionLog(TitanGraph graph) {
return new StandardLogProcessorFramework((StandardTitanGraph)graph);
}
/**
* Returns a {@link TransactionRecovery} process for recovering partially failed transactions. The recovery process
* will start processing the write-ahead transaction log at the specified transaction time.
*
* @param graph
* @param sinceEpoch
* @param unit
* @return
*/
public static TransactionRecovery startTransactionRecovery(TitanGraph graph, long sinceEpoch, TimeUnit unit) {
return new StandardTransactionLogProcessor((StandardTitanGraph)graph, new StandardTimestamp(sinceEpoch,unit));
}
//###################################
// HELPER METHODS
//###################################
private static ReadConfiguration getLocalConfiguration(String shortcutOrFile) {
File file = new File(shortcutOrFile);
if (file.exists()) return getLocalConfiguration(file);
else {
int pos = shortcutOrFile.indexOf(':');
if (pos<0) pos = shortcutOrFile.length();
String backend = shortcutOrFile.substring(0,pos);
Preconditions.checkArgument(Backend.REGISTERED_STORAGE_MANAGERS_SHORTHAND.containsKey(backend.toLowerCase()), "Backend shorthand unknown: %s", backend);
String secondArg = null;
if (pos+1<shortcutOrFile.length()) secondArg = shortcutOrFile.substring(pos + 1).trim();
BaseConfiguration config = new BaseConfiguration();
ModifiableConfiguration writeConfig = new ModifiableConfiguration(ROOT_NS,new CommonsConfiguration(config), BasicConfiguration.Restriction.NONE);
writeConfig.set(STORAGE_BACKEND,backend);
ConfigOption option = Backend.REGISTERED_STORAGE_MANAGERS_SHORTHAND.get(backend.toLowerCase());
if (option==null) {
Preconditions.checkArgument(secondArg==null);
} else if (option==STORAGE_DIRECTORY || option==STORAGE_CONF_FILE) {
Preconditions.checkArgument(StringUtils.isNotBlank(secondArg),"Need to provide additional argument to initialize storage backend");
writeConfig.set(option,getAbsolutePath(secondArg));
} else if (option==STORAGE_HOSTS) {
Preconditions.checkArgument(StringUtils.isNotBlank(secondArg),"Need to provide additional argument to initialize storage backend");
writeConfig.set(option,new String[]{secondArg});
} else throw new IllegalArgumentException("Invalid configuration option for backend "+option);
return new CommonsConfiguration(config);
}
}
/**
* Load a properties file containing a Titan graph configuration.
* <p/>
* <ol>
* <li>Load the file contents into a {@link org.apache.commons.configuration.PropertiesConfiguration}</li>
* <li>For each key that points to a configuration object that is either a directory
* or local file, check
* whether the associated value is a non-null, non-absolute path. If so,
* then prepend the absolute path of the parent directory of the provided configuration {@code file}.
* This has the effect of making non-absolute backend
* paths relative to the config file's directory rather than the JVM's
* working directory.
* <li>Return the {@link ReadConfiguration} for the prepared configuration file</li>
* </ol>
* <p/>
*
* @param file A properties file to load
* @return A configuration derived from {@code file}
*/
@SuppressWarnings("unchecked")
private static ReadConfiguration getLocalConfiguration(File file) {
Preconditions.checkArgument(file != null && file.exists() && file.isFile() && file.canRead(),
"Need to specify a readable configuration file, but was given: %s", file.toString());
try {
PropertiesConfiguration configuration = new PropertiesConfiguration(file);
final File tmpParent = file.getParentFile();
final File configParent;
if (null == tmpParent) {
/*
* null usually means we were given a Titan config file path
* string like "foo.properties" that refers to the current
* working directory of the process.
*/
configParent = new File(System.getProperty("user.dir"));
} else {
configParent = tmpParent;
}
Preconditions.checkNotNull(configParent);
Preconditions.checkArgument(configParent.isDirectory());
// TODO this mangling logic is a relic from the hardcoded string days; it should be deleted and rewritten as a setting on ConfigOption
final Pattern p = Pattern.compile("(" +
Pattern.quote(STORAGE_NS.getName()) + "\\..*" +
"(" + Pattern.quote(STORAGE_DIRECTORY.getName()) + "|" +
Pattern.quote(STORAGE_CONF_FILE.getName()) + ")"
+ "|" +
Pattern.quote(INDEX_NS.getName()) + "\\..*" +
"(" + Pattern.quote(INDEX_DIRECTORY.getName()) + "|" +
Pattern.quote(INDEX_CONF_FILE.getName()) + ")"
+ ")");
final Iterator<String> keysToMangle = Iterators.filter(configuration.getKeys(), new Predicate<String>() {
@Override
public boolean apply(String key) {
if (null == key)
return false;
return p.matcher(key).matches();
}
});
while (keysToMangle.hasNext()) {
String k = keysToMangle.next();
Preconditions.checkNotNull(k);
String s = configuration.getString(k);
Preconditions.checkArgument(StringUtils.isNotBlank(s),"Invalid Configuration: key %s has null empty value",k);
configuration.setProperty(k,getAbsolutePath(configParent,s));
}
return new CommonsConfiguration(configuration);
} catch (ConfigurationException e) {
throw new IllegalArgumentException("Could not load configuration at: " + file, e);
}
}
private static final String getAbsolutePath(String file) {
return getAbsolutePath(new File(System.getProperty("user.dir")), file);
}
private static final String getAbsolutePath(final File configParent, String file) {
File storedir = new File(file);
if (!storedir.isAbsolute()) {
String newFile = configParent.getAbsolutePath() + File.separator + file;
log.debug("Overwrote relative path: was {}, now {}", file, newFile);
return newFile;
} else {
log.debug("Loaded absolute path for key: {}", file);
return file;
}
}
} | true | titan-core_src_main_java_com_thinkaurelius_titan_core_TitanFactory.java |
60 | final Iterator<String> keysToMangle = Iterators.filter(configuration.getKeys(), new Predicate<String>() {
@Override
public boolean apply(String key) {
if (null == key)
return false;
return p.matcher(key).matches();
}
}); | false | titan-core_src_main_java_com_thinkaurelius_titan_core_TitanFactory.java |
61 | public static class Builder extends UserModifiableConfiguration {
private Builder() {
super(GraphDatabaseConfiguration.buildConfiguration());
}
/**
* Configures the provided configuration path to the given value.
*
* @param path
* @param value
* @return
*/
public Builder set(String path, Object value) {
super.set(path, value);
return this;
}
/**
* Opens a Titan graph with the previously configured options.
*
* @return
*/
public TitanGraph open() {
return TitanFactory.open(super.getConfiguration());
}
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_TitanFactory.java |
62 | public interface TitanGraph extends TitanGraphTransaction, ThreadedTransactionalGraph {
/* ---------------------------------------------------------------
* Transactions and general admin
* ---------------------------------------------------------------
*/
/**
* Opens a new thread-independent {@link TitanTransaction}.
* <p/>
* The transaction is open when it is returned but MUST be explicitly closed by calling {@link com.thinkaurelius.titan.core.TitanTransaction#commit()}
* or {@link com.thinkaurelius.titan.core.TitanTransaction#rollback()} when it is no longer needed.
* <p/>
* Note, that this returns a thread independent transaction object. It is not necessary to call this method
* to use Blueprint's standard transaction framework which will automatically start a transaction with the first
* operation on the graph.
*
* @return Transaction object representing a transactional context.
*/
public TitanTransaction newTransaction();
/**
* Returns a {@link TransactionBuilder} to construct a new thread-independent {@link TitanTransaction}.
*
* @return a new TransactionBuilder
* @see TransactionBuilder
* @see #newTransaction()
*/
public TransactionBuilder buildTransaction();
/**
* Returns the management system for this graph instance. The management system provides functionality
* to change global configuration options, install indexes and inspect the graph schema.
* <p />
* The management system operates in its own transactional context which must be explicitly closed.
*
* @return
*/
public TitanManagement getManagementSystem();
/**
* Checks whether the graph is open.
*
* @return true, if the graph is open, else false.
* @see #shutdown()
*/
public boolean isOpen();
/**
* Checks whether the graph is closed.
*
* @return true, if the graph has been closed, else false
*/
public boolean isClosed();
/**
* Closes the graph database.
* <p/>
* Closing the graph database causes a disconnect and possible closing of the underlying storage backend
* and a release of all occupied resources by this graph database.
* Closing a graph database requires that all open thread-independent transactions have been closed -
* otherwise they will be left abandoned.
*
* @throws TitanException if closing the graph database caused errors in the storage backend
*/
public void shutdown() throws TitanException;
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_TitanGraph.java |
63 | public interface TitanGraphQuery<Q extends TitanGraphQuery<Q>> extends GraphQuery {
/* ---------------------------------------------------------------
* Query Specification
* ---------------------------------------------------------------
*/
/**
* The returned element must have a property for the given key that matches the condition according to the
* specified relation
*
* @param key Key that identifies the property
* @param predicate Predicate between property and condition
* @param condition
* @return This query
*/
@Override
public Q has(String key, Predicate predicate, Object condition);
/**
* The returned element must have a property for the given key that matches the condition according to the
* specified relation
*
* @param key Key that identifies the property
* @param predicate Relation between property and condition
* @param condition
* @return This query
*/
public Q has(PropertyKey key, TitanPredicate predicate, Object condition);
@Override
public Q has(String key);
@Override
public Q hasNot(String key);
@Override
public Q has(String key, Object value);
@Override
public Q hasNot(String key, Object value);
@Override
@Deprecated
public <T extends Comparable<T>> Q has(String key, T value, Compare compare);
@Override
public <T extends Comparable<?>> Q interval(String key, T startValue, T endValue);
/**
* Limits the size of the returned result set
*
* @param max The maximum number of results to return
* @return This query
*/
@Override
public Q limit(final int max);
/**
* Orders the element results of this query according
* to their property for the given key in the given order (increasing/decreasing).
*
* @param key The key of the properties on which to order
* @param order the ordering direction
* @return
*/
public Q orderBy(String key, Order order);
/**
* Orders the element results of this query according
* to their property for the given key in the given order (increasing/decreasing).
*
* @param key The key of the properties on which to order
* @param order the ordering direction
* @return
*/
public Q orderBy(PropertyKey key, Order order);
/* ---------------------------------------------------------------
* Query Execution
* ---------------------------------------------------------------
*/
/**
* Returns all vertices that match the conditions.
*
* @return
*/
public Iterable<Vertex> vertices();
/**
* Returns all edges that match the conditions.
*
* @return
*/
public Iterable<Edge> edges();
/**
* Returns all properties that match the conditions
*
* @return
*/
public Iterable<TitanProperty> properties();
/**
* Returns a description of this query for vertices as a {@link QueryDescription} object.
*
* This can be used to inspect the query plan for this query. Note, that calling this method
* does not actually execute the query but only optimizes it and constructs a query plan.
*
* @return A description of this query for vertices
*/
public QueryDescription describeForVertices();
/**
* Returns a description of this query for edges as a {@link QueryDescription} object.
*
* This can be used to inspect the query plan for this query. Note, that calling this method
* does not actually execute the query but only optimizes it and constructs a query plan.
*
* @return A description of this query for edges
*/
public QueryDescription describeForEdges();
/**
* Returns a description of this query for properties as a {@link QueryDescription} object.
*
* This can be used to inspect the query plan for this query. Note, that calling this method
* does not actually execute the query but only optimizes it and constructs a query plan.
*
* @return A description of this query for properties
*/
public QueryDescription describeForProperties();
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_TitanGraphQuery.java |
64 | public interface TitanGraphTransaction extends TransactionalGraph, KeyIndexableGraph, SchemaManager {
/* ---------------------------------------------------------------
* Modifications
* ---------------------------------------------------------------
*/
/**
* Creates a new vertex in the graph with the default vertex label.
*
* @return New vertex in the graph created in the context of this transaction.
*/
public TitanVertex addVertex();
/**
* Creates a new vertex in the graph with the vertex label named by the argument.
*
* @param vertexLabel the name of the vertex label to use
* @return a new vertex in the graph created in the context of this transaction
*/
public TitanVertex addVertexWithLabel(String vertexLabel);
/**
* Creates a new vertex in the graph with the given vertex label.
*
* @param vertexLabel the vertex label which will apply to the new vertex
* @return a new vertex in the graph created in the context of this transaction
*/
public TitanVertex addVertexWithLabel(VertexLabel vertexLabel);
/**
* Retrieves the vertex for the specified id.
*
* @param id id of the vertex to retrieve
* @return vertex with the given id if it exists, else null
* @see #containsVertex
*/
public TitanVertex getVertex(long id);
/**
* Retrieves the vertices for the given ids and returns a map from those ids to the corresponding vertices.
* If a given id does not identify a vertex, it is not included in the returned map
*
* @param ids array of ids for which to retrieve vertices
* @return map from ids to corresponding vertices
* does not identify a vertex
*/
public Map<Long,TitanVertex> getVertices(long... ids);
/**
* Checks whether a vertex with the specified id exists in the graph database.
*
* @param vertexid vertex id
* @return true, if a vertex with that id exists, else false
*/
public boolean containsVertex(long vertexid);
/**
* @return
* @see TitanGraph#query()
*/
public TitanGraphQuery<? extends TitanGraphQuery> query();
/**
* Returns a {@link com.thinkaurelius.titan.core.TitanIndexQuery} to query for vertices or edges against the specified indexing backend using
* the given query string. The query string is analyzed and answered by the underlying storage backend.
* <p/>
* Note, that using indexQuery will may ignore modifications in the current transaction.
*
* @param indexName Name of the indexing backend to query as configured
* @param query Query string
* @return TitanIndexQuery object to query the index directly
*/
public TitanIndexQuery indexQuery(String indexName, String query);
/**
* @return
* @see TitanGraph#multiQuery(com.thinkaurelius.titan.core.TitanVertex...)
*/
public TitanMultiVertexQuery<? extends TitanMultiVertexQuery> multiQuery(TitanVertex... vertices);
/**
* @return
* @see TitanGraph#multiQuery(java.util.Collection)
*/
public TitanMultiVertexQuery<? extends TitanMultiVertexQuery> multiQuery(Collection<TitanVertex> vertices);
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_TitanGraphTransaction.java |
65 | public interface TitanIndexQuery {
/**
* Specifies the maxium number of elements to return
*
* @param limit
* @return
*/
public TitanIndexQuery limit(int limit);
/**
* Specifies the offset of the query. Query results will be retrieved starting at the given offset.
* @param offset
* @return
*/
public TitanIndexQuery offset(int offset);
/**
* Adds the given parameter to the list of parameters of this query.
* Parameters are passed right through to the indexing backend to modify the query behavior.
* @param para
* @return
*/
public TitanIndexQuery addParameter(Parameter para);
/**
* Adds the given parameters to the list of parameters of this query.
* Parameters are passed right through to the indexing backend to modify the query behavior.
* @param paras
* @return
*/
public TitanIndexQuery addParameters(Iterable<Parameter> paras);
/**
* Adds the given parameters to the list of parameters of this query.
* Parameters are passed right through to the indexing backend to modify the query behavior.
* @param paras
* @return
*/
public TitanIndexQuery addParameters(Parameter... paras);
/**
* Sets the element identifier string that is used by this query builder as the token to identifier key references
* in the query string.
* <p/>
* For example, in the query 'v.name: Tom' the element identifier is 'v.'
*
*
* @param identifier The element identifier which must not be blank
* @return This query builder
*/
public TitanIndexQuery setElementIdentifier(String identifier);
/**
* Returns all vertices that match the query in the indexing backend.
*
* @return
*/
public Iterable<Result<Vertex>> vertices();
/**
* Returns all edges that match the query in the indexing backend.
*
* @return
*/
public Iterable<Result<Edge>> edges();
/**
* Returns all properties that match the query in the indexing backend.
*
* @return
*/
public Iterable<Result<TitanProperty>> properties();
/**
* Container of a query result with its score.
* @param <V>
*/
public interface Result<V extends Element> {
/**
* Returns the element that matches the query
*
* @return
*/
public V getElement();
/**
* Returns the score of the result with respect to the query (if available)
* @return
*/
public double getScore();
}
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_TitanIndexQuery.java |
66 | public interface Result<V extends Element> {
/**
* Returns the element that matches the query
*
* @return
*/
public V getElement();
/**
* Returns the score of the result with respect to the query (if available)
* @return
*/
public double getScore();
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_TitanIndexQuery.java |
67 | public interface TitanMultiVertexQuery<Q extends TitanMultiVertexQuery<Q>> extends BaseVertexQuery<Q> {
/* ---------------------------------------------------------------
* Query Specification
* ---------------------------------------------------------------
*/
/**
* Adds the given vertex to the set of vertices against which to execute this query.
*
* @param vertex
* @return this query builder
*/
public TitanMultiVertexQuery addVertex(TitanVertex vertex);
/**
* Adds the given collection of vertices to the set of vertices against which to execute this query.
*
* @param vertices
* @return this query builder
*/
public TitanMultiVertexQuery addAllVertices(Collection<TitanVertex> vertices);
@Override
public Q adjacent(TitanVertex vertex);
@Override
public Q types(RelationType... type);
@Override
public Q labels(String... labels);
@Override
public Q keys(String... keys);
@Override
public Q direction(Direction d);
@Override
public Q has(PropertyKey key, Object value);
@Override
public Q has(EdgeLabel label, TitanVertex vertex);
@Override
public Q has(String key);
@Override
public Q hasNot(String key);
@Override
public Q has(String type, Object value);
@Override
public Q hasNot(String key, Object value);
@Override
public Q has(PropertyKey key, Predicate predicate, Object value);
@Override
public Q has(String key, Predicate predicate, Object value);
@Override
public <T extends Comparable<?>> Q interval(String key, T start, T end);
@Override
public <T extends Comparable<?>> Q interval(PropertyKey key, T start, T end);
@Override
public Q limit(int limit);
@Override
public Q orderBy(String key, Order order);
@Override
public Q orderBy(PropertyKey key, Order order);
/* ---------------------------------------------------------------
* Query execution
* ---------------------------------------------------------------
*/
/**
* Returns an iterable over all incident edges that match this query for each vertex
*
* @return Iterable over all incident edges that match this query for each vertex
*/
public Map<TitanVertex, Iterable<TitanEdge>> titanEdges();
/**
* Returns an iterable over all incident properties that match this query for each vertex
*
* @return Iterable over all incident properties that match this query for each vertex
*/
public Map<TitanVertex, Iterable<TitanProperty>> properties();
/**
* Returns an iterable over all incident relations that match this query for each vertex
*
* @return Iterable over all incident relations that match this query for each vertex
*/
public Map<TitanVertex, Iterable<TitanRelation>> relations();
/**
* Retrieves all vertices connected to each of the query's base vertices by edges
* matching the conditions defined in this query.
* <p/>
*
* @return An iterable of all vertices connected to each of the query's central vertices by matching edges
*/
public Map<TitanVertex, Iterable<TitanVertex>> vertices();
/**
* Retrieves all vertices connected to each of the query's central vertices by edges
* matching the conditions defined in this query.
* <p/>
* The query engine will determine the most efficient way to retrieve the vertices that match this query.
*
* @return A list of all vertices' ids connected to each of the query's central vertex by matching edges
*/
public Map<TitanVertex, VertexList> vertexIds();
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_TitanMultiVertexQuery.java |
68 | public interface TitanProperty extends TitanRelation {
/**
* Returns the property key of this property
*
* @return property key of this property
* @see PropertyKey
*/
public PropertyKey getPropertyKey();
/**
* Returns the vertex on which this property is incident.
*
* @return The vertex of this property.
*/
public TitanVertex getVertex();
/**
* Returns the value of this property (possibly cast to the expected type).
*
* @return value of this property
* @throws ClassCastException if the value cannot be cast to the expected type
*/
public<O> O getValue();
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_TitanProperty.java |
69 | public interface TitanRelation extends TitanElement {
/**
* Establishes a unidirectional edge between this relation and the given vertex for the specified label.
* The label must be defined {@link EdgeLabel#isUnidirected()}.
*
* @param label
* @param vertex
*/
public void setProperty(EdgeLabel label, TitanVertex vertex);
/**
* Returns the vertex associated to this relation by a unidirected edge of the given label or NULL if such does not exist.
*
* @param label
* @return
*/
public TitanVertex getProperty(EdgeLabel label);
/**
* Returns the type of this relation.
* <p/>
* The type is either a label ({@link EdgeLabel} if this relation is an edge or a key ({@link PropertyKey}) if this
* relation is a property.
*
* @return Type of this relation
*/
public RelationType getType();
/**
* Returns the direction of this relation from the perspective of the specified vertex.
*
* @param vertex vertex on which the relation is incident
* @return The direction of this relation from the perspective of the specified vertex.
* @throws InvalidElementException if this relation is not incident on the vertex
*/
public Direction getDirection(TitanVertex vertex);
/**
* Checks whether this relation is incident on the specified vertex.
*
* @param vertex vertex to check incidence for
* @return true, if this relation is incident on the vertex, else false
*/
public boolean isIncidentOn(TitanVertex vertex);
/**
* Checks whether this relation is a loop.
* An relation is a loop if it connects a vertex with itself.
*
* @return true, if this relation is a loop, else false.
*/
boolean isLoop();
/**
* Checks whether this relation is a property.
*
* @return true, if this relation is a property, else false.
* @see TitanProperty
*/
boolean isProperty();
/**
* Checks whether this relation is an edge.
*
* @return true, if this relation is an edge, else false.
* @see TitanEdge
*/
boolean isEdge();
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_TitanRelation.java |
70 | public interface TitanTransaction extends TitanGraphTransaction {
/* ---------------------------------------------------------------
* Modifications
* ---------------------------------------------------------------
*/
/**
* Creates a new vertex in the graph with the given vertex id and the given vertex label.
* Note, that an exception is thrown if the vertex id is not a valid Titan vertex id or if a vertex with the given
* id already exists.
* <p/>
* Custom id setting must be enabled via the configuration option {@link com.thinkaurelius.titan.graphdb.configuration.GraphDatabaseConfiguration#ALLOW_SETTING_VERTEX_ID}.
* <p/>
* Use {@link com.thinkaurelius.titan.core.util.TitanId#toVertexId(long)} to construct a valid Titan vertex id from a user id.
*
* @param id vertex id of the vertex to be created
* @param vertexLabel vertex label for this vertex - can be null if no vertex label should be set.
* @return New vertex
*/
public TitanVertex addVertex(Long id, VertexLabel vertexLabel);
/**
* Creates a new edge connecting the specified vertices.
* <p/>
* Creates and returns a new {@link TitanEdge} with given label connecting the vertices in the order
* specified.
*
* @param label label of the edge to be created
* @param outVertex outgoing vertex of the edge
* @param inVertex incoming vertex of the edge
* @return new edge
*/
public TitanEdge addEdge(TitanVertex outVertex, TitanVertex inVertex, EdgeLabel label);
/**
* Creates a new edge connecting the specified vertices.
* <p/>
* Creates and returns a new {@link TitanEdge} with given label connecting the vertices in the order
* specified.
* <br />
* Automatically creates the edge label if it does not exist and automatic creation of types is enabled. Otherwise,
* this method with throw an {@link IllegalArgumentException}.
*
* @param label label of the edge to be created
* @param outVertex outgoing vertex of the edge
* @param inVertex incoming vertex of the edge
* @return new edge
*/
public TitanEdge addEdge(TitanVertex outVertex, TitanVertex inVertex, String label);
/**
* Creates a new property for the given vertex and key with the specified value.
* <p/>
* Creates and returns a new {@link TitanProperty} with specified property key and the given object being the value.
*
* @param key key of the property to be created
* @param vertex vertex for which to create the property
* @param value value of the property to be created
* @return new property
* @throws IllegalArgumentException if the value does not match the data type of the given property key.
*/
public TitanProperty addProperty(TitanVertex vertex, PropertyKey key, Object value);
/**
* Creates a new property for the given vertex and key with the specified value.
* <p/>
* Creates and returns a new {@link TitanProperty} with specified property key and the given object being the value.
* <br />
* Automatically creates the property key if it does not exist and automatic creation of types is enabled. Otherwise,
* this method with throw an {@link IllegalArgumentException}.
*
* @param key key of the property to be created
* @param vertex vertex for which to create the property
* @param value value of the property to be created
* @return new property
* @throws IllegalArgumentException if the value does not match the data type of the given property key.
*/
public TitanProperty addProperty(TitanVertex vertex, String key, Object value);
/**
* Retrieves all vertices which have a property of the given key with the specified value.
* <p/>
* For this operation to be efficient, please ensure that the given property key is indexed.
* Some storage backends may not support this method without a pre-configured index.
*
* @param key key
* @param value value value
* @return All vertices which have a property of the given key with the specified value.
* @see com.thinkaurelius.titan.core.schema.TitanManagement#buildIndex(String, Class)
*/
public Iterable<TitanVertex> getVertices(PropertyKey key, Object value);
/**
* Retrieves all vertices which have a property of the given key with the specified value.
* <p/>
* For this operation to be efficient, please ensure that the given property key is indexed.
* Some storage backends may not support this method without a pre-configured index.
*
* @param key key
* @param value value value
* @return All edges which have a property of the given key with the specified value.
* @see com.thinkaurelius.titan.core.schema.TitanManagement#buildIndex(String, Class)
*/
public Iterable<TitanEdge> getEdges(PropertyKey key, Object value);
/* ---------------------------------------------------------------
* Closing and admin
* ---------------------------------------------------------------
*/
/**
* Commits and closes the transaction.
* <p/>
* Will attempt to persist all modifications which may result in exceptions in case of persistence failures or
* lock contention.
* <br />
* The call releases data structures if possible. All element references (e.g. vertex objects) retrieved
* through this transaction are stale after the transaction closes and should no longer be used.
*
* @throws com.thinkaurelius.titan.diskstorage.BackendException
* if an error arises during persistence
*/
public void commit();
/**
* Aborts and closes the transaction. Will discard all modifications.
* <p/>
* The call releases data structures if possible. All element references (e.g. vertex objects) retrieved
* through this transaction are stale after the transaction closes and should no longer be used.
*
* @throws com.thinkaurelius.titan.diskstorage.BackendException
* if an error arises when releasing the transaction handle
*/
public void rollback();
/**
* Checks whether the transaction is still open.
*
* @return true, when the transaction is open, else false
*/
public boolean isOpen();
/**
* Checks whether the transaction has been closed.
*
* @return true, if the transaction has been closed, else false
*/
public boolean isClosed();
/**
* Checks whether any changes to the graph database have been made in this transaction.
* <p/>
* A modification may be an edge or vertex update, addition, or deletion.
*
* @return true, if the transaction contains updates, else false.
*/
public boolean hasModifications();
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_TitanTransaction.java |
71 | public interface TitanVertex extends TitanElement, Vertex {
/* ---------------------------------------------------------------
* Creation and modification methods
* ---------------------------------------------------------------
*/
/**
* Creates a new edge incident on this vertex.
* <p/>
* Creates and returns a new {@link TitanEdge} of the specified label with this vertex being the outgoing vertex
* and the given vertex being the incoming vertex.
*
* @param label label of the edge to be created
* @param vertex incoming vertex of the edge to be created
* @return new edge
*/
public TitanEdge addEdge(EdgeLabel label, TitanVertex vertex);
/**
* Creates a new edge incident on this vertex.
* <p/>
* Creates and returns a new {@link TitanEdge} of the specified label with this vertex being the outgoing vertex
* and the given vertex being the incoming vertex.
* <br />
* Automatically creates the edge label if it does not exist and automatic creation of types is enabled. Otherwise,
* this method with throw an {@link IllegalArgumentException}.
*
* @param label label of the edge to be created
* @param vertex incoming vertex of the edge to be created
* @return new edge
*/
public TitanEdge addEdge(String label, TitanVertex vertex);
/**
* Creates a new property for this vertex and given key with the specified value.
* <p/>
* Creates and returns a new {@link TitanProperty} for the given key on this vertex with the specified
* object being the value.
*
* @param key key of the property to be created
* @param value value of the property to be created
* @return New property
* @throws IllegalArgumentException if the value does not match the data type of the property key.
*/
public TitanProperty addProperty(PropertyKey key, Object value);
/**
* Creates a new property for this vertex and given key with the specified value.
* <p/>
* Creates and returns a new {@link TitanProperty} for the given key on this vertex with the specified
* object being the value.
* <br />
* Automatically creates the property key if it does not exist and automatic creation of types is enabled. Otherwise,
* this method with throw an {@link IllegalArgumentException}.
*
* @param key key of the property to be created
* @param value value of the property to be created
* @return New property
* @throws IllegalArgumentException if the value does not match the data type of the property key.
*/
public TitanProperty addProperty(String key, Object value);
/* ---------------------------------------------------------------
* Vertex Label
* ---------------------------------------------------------------
*/
/**
* Returns the name of the vertex label for this vertex.
*
* @return
*/
public String getLabel();
/**
* Returns the vertex label of this vertex.
*
* @return
*/
public VertexLabel getVertexLabel();
/* ---------------------------------------------------------------
* Incident TitanRelation Access methods
* ---------------------------------------------------------------
*/
/**
* Starts a new {@link TitanVertexQuery} for this vertex.
* <p/>
* Initializes and returns a new {@link TitanVertexQuery} based on this vertex.
*
* @return New TitanQuery for this vertex
* @see TitanVertexQuery
*/
public TitanVertexQuery<? extends TitanVertexQuery> query();
/**
* Returns an iterable over all properties incident on this vertex.
* <p/>
* There is no guarantee concerning the order in which the properties are returned. All properties incident
* on this vertex are returned irrespective of their key.
*
* @return {@link Iterable} over all properties incident on this vertex
*/
public Iterable<TitanProperty> getProperties();
/**
* Returns an iterable over all properties of the specified property key incident on this vertex.
* <p/>
* There is no guarantee concerning the order in which the properties are returned. All returned properties are
* of the specified key.
*
* @param key {@link PropertyKey} of the returned properties
* @return {@link Iterable} over all properties of the specified key incident on this vertex
*/
public Iterable<TitanProperty> getProperties(PropertyKey key);
/**
* Returns an iterable over all properties of the specified property key incident on this vertex.
* <p/>
* There is no guarantee concerning the order in which the properties are returned. All returned properties are
* of the specified key.
*
* @param key key of the returned properties
* @return {@link Iterable} over all properties of the specified key incident on this vertex
*/
public Iterable<TitanProperty> getProperties(String key);
/**
* Returns an iterable over all edges of the specified edge label in the given direction incident on this vertex.
* <p/>
* There is no guarantee concerning the order in which the edges are returned. All returned edges have the given
* label and the direction of the edge from the perspective of this vertex matches the specified direction.
*
* @param labels label of the returned edges
* @param d Direction of the returned edges with respect to this vertex
* @return {@link Iterable} over all edges with the given label and direction incident on this vertex
*/
public Iterable<TitanEdge> getTitanEdges(Direction d, EdgeLabel... labels);
/**
* Returns an iterable over all edges of the specified edge label in the given direction incident on this vertex.
* <p/>
* There is no guarantee concerning the order in which the edges are returned. All returned edges have the given
* label and the direction of the edge from the perspective of this vertex matches the specified direction.
*
* @param labels label of the returned edges
* @param d Direction of the returned edges with respect to this vertex
* @return {@link Iterable} over all edges with the given label and direction incident on this vertex
*/
public Iterable<Edge> getEdges(Direction d, String... labels);
/**
* Returns an iterable over all edges incident on this vertex.
* <p/>
* There is no guarantee concerning the order in which the edges are returned.
*
* @return {@link Iterable} over all edges incident on this vertex
*/
public Iterable<TitanEdge> getEdges();
/**
* Returns an iterable over all relations incident on this vertex.
* <p/>
* There is no guarantee concerning the order in which the relations are returned. Note, that this
* method potentially returns both {@link TitanEdge} and {@link TitanProperty}.
*
* @return {@link Iterable} over all properties and edges incident on this vertex.
*/
public Iterable<TitanRelation> getRelations();
/**
* Returns the number of edges incident on this vertex.
* <p/>
* Returns the total number of edges irrespective of label and direction.
* Note, that loop edges, i.e. edges with identical in- and outgoing vertex, are counted twice.
*
* @return The number of edges incident on this vertex.
*/
public long getEdgeCount();
/**
* Returns the number of properties incident on this vertex.
* <p/>
* Returns the total number of properties irrespective of key.
*
* @return The number of properties incident on this vertex.
*/
public long getPropertyCount();
/**
* Checks whether this vertex has at least one incident edge.
* In other words, it returns getEdgeCount()>0, but might be implemented more efficiently.
*
* @return true, if this vertex has at least one incident edge, else false
*/
public boolean isConnected();
/**
* Checks whether this entity has been loaded into the current transaction and modified.
*
* @return True, has been loaded and modified, else false.
*/
public boolean isModified();
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_TitanVertex.java |
72 | public interface TitanVertexQuery<Q extends TitanVertexQuery<Q>> extends BaseVertexQuery<Q>, VertexQuery {
/* ---------------------------------------------------------------
* Query Specification (overwrite to merge BaseVertexQuery with Blueprint's VertexQuery)
* ---------------------------------------------------------------
*/
@Override
public Q adjacent(TitanVertex vertex);
@Override
public Q types(RelationType... type);
@Override
public Q labels(String... labels);
@Override
public Q keys(String... keys);
@Override
public Q direction(Direction d);
@Override
public Q has(PropertyKey key, Object value);
@Override
public Q has(EdgeLabel label, TitanVertex vertex);
@Override
public Q has(String key);
@Override
public Q hasNot(String key);
@Override
public Q has(String type, Object value);
@Override
public Q hasNot(String key, Object value);
@Override
public Q has(PropertyKey key, Predicate predicate, Object value);
@Override
public Q has(String key, Predicate predicate, Object value);
@Override
public <T extends Comparable<?>> Q interval(String key, T start, T end);
@Override
public <T extends Comparable<?>> Q interval(PropertyKey key, T start, T end);
@Override
public Q limit(int limit);
@Override
public Q orderBy(String key, Order order);
@Override
public Q orderBy(PropertyKey key, Order order);
/* ---------------------------------------------------------------
* Query execution
* ---------------------------------------------------------------
*/
/**
* Returns an iterable over all incident edges that match this query
*
* @return Iterable over all incident edges that match this query
*/
public Iterable<Edge> edges();
/**
* Returns an iterable over all incident edges that match this query. Returns edges as {@link TitanEdge}.
*
* @return Iterable over all incident edges that match this query
*/
public Iterable<TitanEdge> titanEdges();
/**
* Returns an iterable over all incident properties that match this query
*
* @return Iterable over all incident properties that match this query
*/
public Iterable<TitanProperty> properties();
/**
* Returns an iterable over all incident relations that match this query
*
* @return Iterable over all incident relations that match this query
*/
public Iterable<TitanRelation> relations();
/**
* Returns the number of edges that match this query
*
* @return Number of edges that match this query
*/
public long count();
/**
* Returns the number of properties that match this query
*
* @return Number of properties that match this query
*/
public long propertyCount();
/**
* Retrieves all vertices connected to this query's base vertex by edges
* matching the conditions defined in this query.
* <p/>
* The query engine will determine the most efficient way to retrieve the vertices that match this query.
*
* @return A list of all vertices connected to this query's base vertex by matching edges
*/
@Override
public VertexList vertexIds();
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_TitanVertexQuery.java |
73 | public interface TransactionBuilder {
/**
* Makes the transaction read only. Any writes will cause an exception.
* Read-only transactions do not have to maintain certain data structures and can hence be more efficient.
*
* @return
*/
public TransactionBuilder readOnly();
/**
* Enabling batch loading disables a number of consistency checks inside Titan to speed up the ingestion of
* data under the assumptions that inconsistencies are resolved prior to loading.
*
* @return
*/
public TransactionBuilder enableBatchLoading();
/**
* Disables batch loading by ensuring that consistency checks are applied in this transaction. This allows
* an individual transaction to use consistency checks when the graph as a whole is configured to not use them,
* which is useful when defining schema elements in a graph with batch-loading enabled.
*
* @return
*/
public TransactionBuilder disableBatchLoading();
/**
* Configures the size of the internal caches used in the transaction.
*
* @param size
* @return
*/
public TransactionBuilder setVertexCacheSize(int size);
/**
* Configures the initial size of the map of modified vertices held by this
* transaction. This is a performance hint, not a hard upper bound. The map
* will grow if the transaction ends up modifying more vertices than
* expected.
*
* @param size initial size of the transaction's dirty vertex collection
* @return
*/
public TransactionBuilder setDirtyVertexSize(int size);
/**
* Enables/disables checks that verify that each vertex actually exists in the underlying data store when it is retrieved.
* This might be useful to address common data degradation issues but has adverse impacts on performance due to
* repeated existence checks.
* <p/>
* Note, that these checks apply to vertex retrievals inside the query execution engine and not to vertex ids provided
* by the user.
*
* @param enabled
* @return
*/
public TransactionBuilder checkInternalVertexExistence(boolean enabled);
/**
* Enables/disables checking whether the vertex with a user provided id indeed exists. If the user is absolutely sure
* that the vertices for the ids provided in this transaction exist in the underlying data store, then disabling the
* vertex existence check will improve performance because it eliminates a database call.
* However, if a provided vertex id does not exist in the database and checking is disabled, Titan will assume it
* exists which can lead to data and query inconsistencies.
*
* @param enabled
* @return
*/
public TransactionBuilder checkExternalVertexExistence(boolean enabled);
/**
* Enables/disables consistency checking and locking for this transaction. Disabling consistency checks improves
* performance but requires that the user ensures consistency at the application level. Use with great care.
*
* @param enabled
* @return
*/
public TransactionBuilder consistencyChecks(boolean enabled);
/**
* Sets the timestamp for this transaction. The transaction will be recorded
* with this timestamp in those storage backends where the timestamp is
* recorded.
*
* @param timestampSinceEpoch
* number of units elapsed since the UNIX Epoch, that is,
* 00:00:00 UTC, Thursday, 1 January 1970
* @param unit
* units of the {@code timestampSinceEpoch argument}
* @return
*/
public TransactionBuilder setCommitTime(long timestampSinceEpoch, TimeUnit unit);
/**
* Sets the group name for this transaction which provides a way for gathering
* reporting on multiple transactions into one group.
*
* By setting a group one enables Metrics for this transaction, and defines what string
* should start the transaction's metric names.
* <p>
* If null, Metrics collection is totally disabled for this transaction.
* <p>
* If empty, Metrics collection is enabled, but there will be no prefix.
* Where the default setting would generate metrics names in the form
* "prefix.x.y.z", this transaction will instead use metric names in the
* form "x.y.z".
* <p>
* If nonempty, Metrics collection is enabled and the prefix will be used
* for all of this transaction's measurements.
* <p>
* Note: setting this to a non-null value only partially overrides
* {@link GraphDatabaseConfiguration#BASIC_METRICS} = false in the graph
* database configuration. When Metrics are disabled at the graph level and
* enabled at the transaction level, storage backend timings and counters
* will remain disabled.
* <p>
* The default value is
* {@link GraphDatabaseConfiguration#METRICS_PREFIX_DEFAULT}.
*
* Sets the name prefix used for Metrics recorded by this transaction. If
* metrics is enabled via {@link GraphDatabaseConfiguration#BASIC_METRICS},
* this string will be prepended to all Titan metric names.
*
* @param name
* Metric name prefix for this transaction
* @return
*/
public TransactionBuilder setGroupName(String name);
/**
* Name of the log to be used for logging the mutations in this transaction. If no log identifier is set,
* then this transaction will not be logged.
*
* @param logName
* @return
*/
public TransactionBuilder setLogIdentifier(String logName);
/**
* Configures this transaction such that queries against partitioned vertices are
* restricted to the given partitions.
*
* @param partitions
* @return
*/
public TransactionBuilder setRestrictedPartitions(int[] partitions);
/**
* Configures a custom option on this transaction which will be passed through to the storage and indexing backends.
* @param k
* @param v
* @return
*/
public TransactionBuilder setCustomOption(String k, Object v);
/**
* Starts and returns the transaction build by this builder
*
* @return A new transaction configured according to this builder
*/
public TitanTransaction start();
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_TransactionBuilder.java |
74 | public interface VertexLabel extends TitanVertex, TitanSchemaType {
/**
* Whether vertices with this label are partitioned.
*
* @return
*/
public boolean isPartitioned();
/**
* Whether vertices with this label are static, that is, immutable beyond the transaction
* in which they were created.
*
* @return
*/
public boolean isStatic();
//TTL
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_VertexLabel.java |
75 | public interface VertexList extends Iterable<TitanVertex> {
/**
* Returns the number of vertices in this list.
*
* @return Number of vertices in the list.
*/
public int size();
/**
* Returns the vertex at a given position in the list.
*
* @param pos Position for which to retrieve the vertex.
* @return TitanVertex at the given position
*/
public TitanVertex get(int pos);
/**
* Sorts this list according to vertex ids in increasing order.
* If the list is already sorted, invoking this method incurs no cost.
*
* @throws UnsupportedOperationException If not all vertices in this list have an id
*/
public void sort();
/**
* Whether this list of vertices is sorted by id in increasing order.
*
* @return
*/
public boolean isSorted();
/**
* Returns a sub list of this list of vertices from the given position with the given number of vertices.
*
* @param fromPosition
* @param length
* @return
*/
public VertexList subList(int fromPosition, int length);
/**
* Returns a list of ids of all vertices in this list of vertices in the same order of the original vertex list.
* <p/>
* Uses an efficient primitive variable-sized array.
*
* @return A list of idAuthorities of all vertices in this list of vertices in the same order of the original vertex list.
* @see AbstractLongList
*/
public LongArrayList getIDs();
/**
* Returns the id of the vertex at the specified position
*
* @param pos The position of the vertex in the list
* @return The id of that vertex
*/
public long getID(int pos);
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_VertexList.java |
76 | public interface AttributeHandler<V> {
/**
* Verifies the given (not-null) attribute value is valid.
* Throws an {@link IllegalArgumentException} if the value is invalid,
* otherwise simply returns.
*
* @param value to verify
*/
public void verifyAttribute(V value);
/**
* Converts the given (not-null) value to the expected datatype V.
* The given object will NOT be of type V.
* Throws an {@link IllegalArgumentException} if it cannot be converted.
*
* @param value to convert
* @return converted to expected datatype
*/
public V convert(Object value);
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_AttributeHandler.java |
77 | public interface AttributeSerializer<V> extends AttributeHandler<V> {
/**
* Reads an attribute from the given ReadBuffer.
* <p/>
* It is expected that this read operation adjusts the position in the ReadBuffer to after the attribute value.
*
* @param buffer ReadBuffer to read attribute from
* @return Read attribute
*/
public V read(ScanBuffer buffer);
/**
* Writes the attribute value to the given WriteBuffer.
* <p/>
* It is expected that this write operation adjusts the position in the WriteBuffer to after the attribute value.
*
* @param buffer WriteBuffer to write attribute to
* @param attribute Attribute to write to WriteBuffer
*/
public void write(WriteBuffer buffer, V attribute);
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_AttributeSerializer.java |
78 | public enum Cmp implements TitanPredicate {
EQUAL {
@Override
public boolean isValidValueType(Class<?> clazz) {
return true;
}
@Override
public boolean isValidCondition(Object condition) {
return true;
}
@Override
public boolean evaluate(Object value, Object condition) {
if (condition==null) {
return value==null;
} else {
return condition.equals(value);
}
}
@Override
public String toString() {
return "=";
}
@Override
public TitanPredicate negate() {
return NOT_EQUAL;
}
},
NOT_EQUAL {
@Override
public boolean isValidValueType(Class<?> clazz) {
return true;
}
@Override
public boolean isValidCondition(Object condition) {
return true;
}
@Override
public boolean evaluate(Object value, Object condition) {
if (condition==null) {
return value!=null;
} else {
return !condition.equals(value);
}
}
@Override
public String toString() {
return "<>";
}
@Override
public TitanPredicate negate() {
return EQUAL;
}
},
LESS_THAN {
@Override
public boolean isValidValueType(Class<?> clazz) {
Preconditions.checkNotNull(clazz);
return Comparable.class.isAssignableFrom(clazz);
}
@Override
public boolean isValidCondition(Object condition) {
return condition!=null && condition instanceof Comparable;
}
@Override
public boolean evaluate(Object value, Object condition) {
Integer cmp = AttributeUtil.compare(value,condition);
return cmp!=null?cmp<0:false;
}
@Override
public String toString() {
return "<";
}
@Override
public TitanPredicate negate() {
return GREATER_THAN_EQUAL;
}
},
LESS_THAN_EQUAL {
@Override
public boolean isValidValueType(Class<?> clazz) {
Preconditions.checkNotNull(clazz);
return Comparable.class.isAssignableFrom(clazz);
}
@Override
public boolean isValidCondition(Object condition) {
return condition!=null && condition instanceof Comparable;
}
@Override
public boolean evaluate(Object value, Object condition) {
Integer cmp = AttributeUtil.compare(value,condition);
return cmp!=null?cmp<=0:false;
}
@Override
public String toString() {
return "<=";
}
@Override
public TitanPredicate negate() {
return GREATER_THAN;
}
},
GREATER_THAN {
@Override
public boolean isValidValueType(Class<?> clazz) {
Preconditions.checkNotNull(clazz);
return Comparable.class.isAssignableFrom(clazz);
}
@Override
public boolean isValidCondition(Object condition) {
return condition!=null && condition instanceof Comparable;
}
@Override
public boolean evaluate(Object value, Object condition) {
Integer cmp = AttributeUtil.compare(value,condition);
return cmp!=null?cmp>0:false;
}
@Override
public String toString() {
return ">";
}
@Override
public TitanPredicate negate() {
return LESS_THAN_EQUAL;
}
},
GREATER_THAN_EQUAL {
@Override
public boolean isValidValueType(Class<?> clazz) {
Preconditions.checkNotNull(clazz);
return Comparable.class.isAssignableFrom(clazz);
}
@Override
public boolean isValidCondition(Object condition) {
return condition!=null && condition instanceof Comparable;
}
@Override
public boolean evaluate(Object value, Object condition) {
Integer cmp = AttributeUtil.compare(value,condition);
return cmp!=null?cmp>=0:false;
}
@Override
public String toString() {
return ">=";
}
@Override
public TitanPredicate negate() {
return LESS_THAN;
}
};
@Override
public boolean hasNegation() {
return true;
}
@Override
public boolean isQNF() {
return true;
}
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Cmp.java |
79 | EQUAL {
@Override
public boolean isValidValueType(Class<?> clazz) {
return true;
}
@Override
public boolean isValidCondition(Object condition) {
return true;
}
@Override
public boolean evaluate(Object value, Object condition) {
if (condition==null) {
return value==null;
} else {
return condition.equals(value);
}
}
@Override
public String toString() {
return "=";
}
@Override
public TitanPredicate negate() {
return NOT_EQUAL;
}
}, | false | titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Cmp.java |
80 | NOT_EQUAL {
@Override
public boolean isValidValueType(Class<?> clazz) {
return true;
}
@Override
public boolean isValidCondition(Object condition) {
return true;
}
@Override
public boolean evaluate(Object value, Object condition) {
if (condition==null) {
return value!=null;
} else {
return !condition.equals(value);
}
}
@Override
public String toString() {
return "<>";
}
@Override
public TitanPredicate negate() {
return EQUAL;
}
}, | false | titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Cmp.java |
81 | LESS_THAN {
@Override
public boolean isValidValueType(Class<?> clazz) {
Preconditions.checkNotNull(clazz);
return Comparable.class.isAssignableFrom(clazz);
}
@Override
public boolean isValidCondition(Object condition) {
return condition!=null && condition instanceof Comparable;
}
@Override
public boolean evaluate(Object value, Object condition) {
Integer cmp = AttributeUtil.compare(value,condition);
return cmp!=null?cmp<0:false;
}
@Override
public String toString() {
return "<";
}
@Override
public TitanPredicate negate() {
return GREATER_THAN_EQUAL;
}
}, | false | titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Cmp.java |
82 | LESS_THAN_EQUAL {
@Override
public boolean isValidValueType(Class<?> clazz) {
Preconditions.checkNotNull(clazz);
return Comparable.class.isAssignableFrom(clazz);
}
@Override
public boolean isValidCondition(Object condition) {
return condition!=null && condition instanceof Comparable;
}
@Override
public boolean evaluate(Object value, Object condition) {
Integer cmp = AttributeUtil.compare(value,condition);
return cmp!=null?cmp<=0:false;
}
@Override
public String toString() {
return "<=";
}
@Override
public TitanPredicate negate() {
return GREATER_THAN;
}
}, | false | titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Cmp.java |
83 | GREATER_THAN {
@Override
public boolean isValidValueType(Class<?> clazz) {
Preconditions.checkNotNull(clazz);
return Comparable.class.isAssignableFrom(clazz);
}
@Override
public boolean isValidCondition(Object condition) {
return condition!=null && condition instanceof Comparable;
}
@Override
public boolean evaluate(Object value, Object condition) {
Integer cmp = AttributeUtil.compare(value,condition);
return cmp!=null?cmp>0:false;
}
@Override
public String toString() {
return ">";
}
@Override
public TitanPredicate negate() {
return LESS_THAN_EQUAL;
}
}, | false | titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Cmp.java |
84 | GREATER_THAN_EQUAL {
@Override
public boolean isValidValueType(Class<?> clazz) {
Preconditions.checkNotNull(clazz);
return Comparable.class.isAssignableFrom(clazz);
}
@Override
public boolean isValidCondition(Object condition) {
return condition!=null && condition instanceof Comparable;
}
@Override
public boolean evaluate(Object value, Object condition) {
Integer cmp = AttributeUtil.compare(value,condition);
return cmp!=null?cmp>=0:false;
}
@Override
public String toString() {
return ">=";
}
@Override
public TitanPredicate negate() {
return LESS_THAN;
}
}; | false | titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Cmp.java |
85 | public enum Contain implements TitanPredicate {
/**
* Whether an element is in a collection
*/
IN {
@Override
public boolean evaluate(Object value, Object condition) {
Preconditions.checkArgument(isValidCondition(condition), "Invalid condition provided: %s", condition);
Collection col = (Collection) condition;
return col.contains(value);
}
@Override
public TitanPredicate negate() {
return NOT_IN;
}
},
/**
* Whether an element is not in a collection
*/
NOT_IN {
@Override
public boolean evaluate(Object value, Object condition) {
Preconditions.checkArgument(isValidCondition(condition), "Invalid condition provided: %s", condition);
Collection col = (Collection) condition;
return !col.contains(value);
}
@Override
public TitanPredicate negate() {
return IN;
}
};
private static final Logger log = LoggerFactory.getLogger(Contain.class);
@Override
public boolean isValidValueType(Class<?> clazz) {
return true;
}
@Override
public boolean isValidCondition(Object condition) {
return condition != null && (condition instanceof Collection) && !((Collection) condition).isEmpty();
}
@Override
public boolean hasNegation() {
return true;
}
@Override
public boolean isQNF() {
return false;
}
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Contain.java |
86 | IN {
@Override
public boolean evaluate(Object value, Object condition) {
Preconditions.checkArgument(isValidCondition(condition), "Invalid condition provided: %s", condition);
Collection col = (Collection) condition;
return col.contains(value);
}
@Override
public TitanPredicate negate() {
return NOT_IN;
}
}, | false | titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Contain.java |
87 | NOT_IN {
@Override
public boolean evaluate(Object value, Object condition) {
Preconditions.checkArgument(isValidCondition(condition), "Invalid condition provided: %s", condition);
Collection col = (Collection) condition;
return !col.contains(value);
}
@Override
public TitanPredicate negate() {
return IN;
}
}; | false | titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Contain.java |
88 | public class Decimal extends AbstractDecimal {
public static final int DECIMALS = 3;
public static final Decimal MIN_VALUE = new Decimal(minDoubleValue(DECIMALS));
public static final Decimal MAX_VALUE = new Decimal(maxDoubleValue(DECIMALS));
private Decimal() {}
public Decimal(double value) {
super(value, DECIMALS);
}
private Decimal(long format) {
super(format, DECIMALS);
}
public static class DecimalSerializer extends AbstractDecimalSerializer<Decimal> {
public DecimalSerializer() {
super(DECIMALS, Decimal.class);
}
@Override
protected Decimal construct(long format, int decimals) {
assert decimals==DECIMALS;
return new Decimal(format);
}
}
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Decimal.java |
89 | public static class DecimalSerializer extends AbstractDecimalSerializer<Decimal> {
public DecimalSerializer() {
super(DECIMALS, Decimal.class);
}
@Override
protected Decimal construct(long format, int decimals) {
assert decimals==DECIMALS;
return new Decimal(format);
}
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Decimal.java |
90 | public interface Duration extends Comparable<Duration> {
/**
* Returns the length of this duration in the given {@link TimeUnit}.
*
* @param unit
* @return
*/
public long getLength(TimeUnit unit);
/**
* Whether this duration is of zero length.
* @return
*/
public boolean isZeroLength();
/**
* Returns the native unit used by this duration. The actual time length is specified in this unit of time.
* </p>
* @return
*/
public TimeUnit getNativeUnit();
/**
* Returns a new duration that equals the length of this duration minus the length of the given duration
* in the unit of this duration.
*
* @param subtrahend
* @return
*/
public Duration sub(Duration subtrahend);
/**
* Returns a new duration that equals the combined length of this and the given duration in the
* unit of this duration.
*
* @param addend
* @return
*/
public Duration add(Duration addend);
/**
* Multiplies the length of this duration by the given multiplier. The multiplier must be a non-negative number.
*
* @param multiplier
* @return
*/
public Duration multiply(double multiplier);
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Duration.java |
91 | public enum Geo implements TitanPredicate {
/**
* Whether the intersection between two geographic regions is non-empty
*/
INTERSECT {
@Override
public boolean evaluate(Object value, Object condition) {
Preconditions.checkArgument(condition instanceof Geoshape);
if (value == null) return false;
Preconditions.checkArgument(value instanceof Geoshape);
return ((Geoshape) value).intersect((Geoshape) condition);
}
@Override
public String toString() {
return "intersect";
}
@Override
public boolean hasNegation() {
return true;
}
@Override
public TitanPredicate negate() {
return DISJOINT;
}
},
/**
* Whether the intersection between two geographic regions is empty
*/
DISJOINT {
@Override
public boolean evaluate(Object value, Object condition) {
Preconditions.checkArgument(condition instanceof Geoshape);
if (value == null) return false;
Preconditions.checkArgument(value instanceof Geoshape);
return ((Geoshape) value).disjoint((Geoshape) condition);
}
@Override
public String toString() {
return "disjoint";
}
@Override
public boolean hasNegation() {
return true;
}
@Override
public TitanPredicate negate() {
return INTERSECT;
}
},
/**
* Whether one geographic region is completely contains within another
*/
WITHIN {
@Override
public boolean evaluate(Object value, Object condition) {
Preconditions.checkArgument(condition instanceof Geoshape);
if (value == null) return false;
Preconditions.checkArgument(value instanceof Geoshape);
return ((Geoshape) value).within((Geoshape) condition);
}
@Override
public String toString() {
return "within";
}
@Override
public boolean hasNegation() {
return false;
}
@Override
public TitanPredicate negate() {
throw new UnsupportedOperationException();
}
};
@Override
public boolean isValidCondition(Object condition) {
return condition != null && condition instanceof Geoshape;
}
@Override
public boolean isValidValueType(Class<?> clazz) {
Preconditions.checkNotNull(clazz);
return clazz.equals(Geoshape.class);
}
@Override
public boolean isQNF() {
return true;
}
} | false | titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Geo.java |
92 | INTERSECT {
@Override
public boolean evaluate(Object value, Object condition) {
Preconditions.checkArgument(condition instanceof Geoshape);
if (value == null) return false;
Preconditions.checkArgument(value instanceof Geoshape);
return ((Geoshape) value).intersect((Geoshape) condition);
}
@Override
public String toString() {
return "intersect";
}
@Override
public boolean hasNegation() {
return true;
}
@Override
public TitanPredicate negate() {
return DISJOINT;
}
}, | false | titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Geo.java |
93 | DISJOINT {
@Override
public boolean evaluate(Object value, Object condition) {
Preconditions.checkArgument(condition instanceof Geoshape);
if (value == null) return false;
Preconditions.checkArgument(value instanceof Geoshape);
return ((Geoshape) value).disjoint((Geoshape) condition);
}
@Override
public String toString() {
return "disjoint";
}
@Override
public boolean hasNegation() {
return true;
}
@Override
public TitanPredicate negate() {
return INTERSECT;
}
}, | false | titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Geo.java |
94 | WITHIN {
@Override
public boolean evaluate(Object value, Object condition) {
Preconditions.checkArgument(condition instanceof Geoshape);
if (value == null) return false;
Preconditions.checkArgument(value instanceof Geoshape);
return ((Geoshape) value).within((Geoshape) condition);
}
@Override
public String toString() {
return "within";
}
@Override
public boolean hasNegation() {
return false;
}
@Override
public TitanPredicate negate() {
throw new UnsupportedOperationException();
}
}; | false | titan-core_src_main_java_com_thinkaurelius_titan_core_attribute_Geo.java |
End of preview. Expand
in Dataset Viewer.
- Downloads last month
- 28