Java Code Examples for com.thinkaurelius.titan.core.TitanFactory

The following are top voted examples for showing how to use com.thinkaurelius.titan.core.TitanFactory. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: keti   File: GraphConfig.java   Source Code and License 8 votes vote down vote up
public Graph createGraph() throws InterruptedException {
    Graph newGraph;
    if (this.cassandraEnabled) {
        Builder titanBuilder = TitanFactory.build().set("storage.backend", "cassandra")
                .set("storage.cassandra.keyspace", this.cassandraKeyspace)
                .set("storage.hostname", Arrays.asList(hostname.split(","))).set("storage.port", this.port)
                .set("cache.db-cache", this.cacheEnabled).set("cache.db-cache-clean-wait", this.titanCacheCleanWait)
                .set("cache.db-cache-time", this.titanCacheTime).set("cache.db-cache-size", this.titanCacheSize);
        if (StringUtils.isNotEmpty(this.username)) {
            titanBuilder = titanBuilder.set("storage.username", this.username);
        }
        if (StringUtils.isNotEmpty(this.password)) {
            titanBuilder = titanBuilder.set("storage.password", this.password);
        }
        newGraph = titanBuilder.open();
    } else {
        newGraph = TitanFactory.build().set("storage.backend", "inmemory").open();
    }
    createSchemaElements(newGraph);
    LOGGER.info("Initialized titan db.");
    return newGraph;
}
 
Example 2
Project: mizo   File: MizoRDD.java   Source Code and License 6 votes vote down vote up
/**
 * Given a path for Titan config file, connects and gets the internal Titan types,
 * converting them to MizoTitanRelationTypes mapped by type-ids
 * @param titanConfigPath Path to Titan's config path
 * @return Mapping between relation type-ids to InternalRelationType instances
 */
protected static HashMap<Long, MizoTitanRelationType> loadRelationTypes(String titanConfigPath) {
    TitanGraph g = TitanFactory.open(titanConfigPath);
    StandardTitanTx tx = (StandardTitanTx)g.buildTransaction().readOnly().start();

    HashMap<Long, MizoTitanRelationType> relations = Maps.newHashMap();

    tx.query()
            .has(BaseKey.SchemaCategory, Contain.IN, Lists.newArrayList(TitanSchemaCategory.values()))
            .vertices()
            .forEach(v -> {
                if (v instanceof InternalRelationType)
                    relations.put(v.longId(), new MizoTitanRelationType((InternalRelationType)v));
            });

    tx.close();

    try {
        ((StandardTitanGraph)g).getBackend().close();
    } catch (BackendException e) {
        e.printStackTrace();
    }

    return relations;
}
 
Example 3
Project: titan1withtp3.1   File: CassandraGraphTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testGraphConfigUsedByThreadBoundTx() {
    close();
    WriteConfiguration wc = getConfiguration();
    wc.set(ConfigElement.getPath(CASSANDRA_READ_CONSISTENCY), "ALL");
    wc.set(ConfigElement.getPath(CASSANDRA_WRITE_CONSISTENCY), "LOCAL_QUORUM");

    graph = (StandardTitanGraph) TitanFactory.open(wc);

    StandardTitanTx tx = (StandardTitanTx)graph.getCurrentThreadTx();
    assertEquals("ALL",
            tx.getTxHandle().getBaseTransactionConfig().getCustomOptions()
                    .get(AbstractCassandraStoreManager.CASSANDRA_READ_CONSISTENCY));
    assertEquals("LOCAL_QUORUM",
            tx.getTxHandle().getBaseTransactionConfig().getCustomOptions()
                    .get(AbstractCassandraStoreManager.CASSANDRA_WRITE_CONSISTENCY));
}
 
Example 4
Project: titan1withtp3.1   File: CassandraGraphTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testGraphConfigUsedByTx() {
    close();
    WriteConfiguration wc = getConfiguration();
    wc.set(ConfigElement.getPath(CASSANDRA_READ_CONSISTENCY), "TWO");
    wc.set(ConfigElement.getPath(CASSANDRA_WRITE_CONSISTENCY), "THREE");

    graph = (StandardTitanGraph) TitanFactory.open(wc);

    StandardTitanTx tx = (StandardTitanTx)graph.newTransaction();
    assertEquals("TWO",
            tx.getTxHandle().getBaseTransactionConfig().getCustomOptions()
                    .get(AbstractCassandraStoreManager.CASSANDRA_READ_CONSISTENCY));
    assertEquals("THREE",
            tx.getTxHandle().getBaseTransactionConfig().getCustomOptions()
                    .get(AbstractCassandraStoreManager.CASSANDRA_WRITE_CONSISTENCY));
    tx.rollback();
}
 
Example 5
Project: titan1withtp3.1   File: CassandraGraphTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testCustomConfigUsedByTx() {
    close();
    WriteConfiguration wc = getConfiguration();
    wc.set(ConfigElement.getPath(CASSANDRA_READ_CONSISTENCY), "ALL");
    wc.set(ConfigElement.getPath(CASSANDRA_WRITE_CONSISTENCY), "ALL");

    graph = (StandardTitanGraph) TitanFactory.open(wc);

    StandardTitanTx tx = (StandardTitanTx)graph.buildTransaction()
            .customOption(ConfigElement.getPath(CASSANDRA_READ_CONSISTENCY), "ONE")
            .customOption(ConfigElement.getPath(CASSANDRA_WRITE_CONSISTENCY), "TWO").start();

    assertEquals("ONE",
            tx.getTxHandle().getBaseTransactionConfig().getCustomOptions()
                    .get(AbstractCassandraStoreManager.CASSANDRA_READ_CONSISTENCY));
    assertEquals("TWO",
            tx.getTxHandle().getBaseTransactionConfig().getCustomOptions()
                    .get(AbstractCassandraStoreManager.CASSANDRA_WRITE_CONSISTENCY));
    tx.rollback();
}
 
Example 6
Project: titan1withtp3.1   File: ElasticSearchConfigTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testTitanFactoryBuilder()
{
    String baseDir = Joiner.on(File.separator).join("target", "es", "titanfactory_jvmlocal_ext");
    TitanFactory.Builder builder = TitanFactory.build();
    builder.set("storage.backend", "inmemory");
    builder.set("index." + INDEX_NAME + ".elasticsearch.interface", "NODE");
    builder.set("index." + INDEX_NAME + ".elasticsearch.ext.node.data", "true");
    builder.set("index." + INDEX_NAME + ".elasticsearch.ext.node.client", "false");
    builder.set("index." + INDEX_NAME + ".elasticsearch.ext.node.local", "true");
    builder.set("index." + INDEX_NAME + ".elasticsearch.ext.path.data", baseDir + File.separator + "data");
    builder.set("index." + INDEX_NAME + ".elasticsearch.ext.path.work", baseDir + File.separator + "work");
    builder.set("index." + INDEX_NAME + ".elasticsearch.ext.path.logs", baseDir + File.separator + "logs");
    TitanGraph graph = builder.open(); // Must not throw an exception
    assertTrue(graph.isOpen());
    graph.close();
}
 
Example 7
Project: titan1withtp3.1   File: Driver.java   Source Code and License 6 votes vote down vote up
private void doWork()
    {
        TitanGraph graph = TitanFactory.build().set("storage.backend", "inmemory").open();

        // do "auto" transaction work
        graph.addVertex("type", "human");
        graph.tx().commit();

        // do "named" transaction work
//        TitanTransaction tx = graph.buildTransaction().logIdentifier("david1").start();
//        Vertex v = tx.addVertex("type", "dog");
//        Long id = (Long)v.id();
//        tx.commit();

//        GraphTraversalSource g = graph.traversal();
//        Vertex v1 = g.V(id.longValue()).next();
//        v1.remove();

        graph.close();
    }
 
Example 8
Project: titan-tp3-java-example   File: JavaExample.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
    String dataDir = "./data";
    TitanGraph graph = TitanFactory.open("berkeleyje:" + dataDir);

    // see org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerFactory.generateClassic()
    final Vertex marko = graph.addVertex("name", "marko", "age", 29);
    final Vertex vadas = graph.addVertex("name", "vadas", "age", 27);
    final Vertex lop = graph.addVertex("name", "lop", "lang", "java");
    final Vertex josh = graph.addVertex("name", "josh", "age", 32);
    final Vertex ripple = graph.addVertex("name", "ripple", "lang", "java");
    final Vertex peter = graph.addVertex("name", "peter", "age", 35);
    marko.addEdge("knows", vadas, "weight", 0.5f);
    marko.addEdge("knows", josh, "weight", 1.0f);
    marko.addEdge("created", lop, "weight", 0.4f);
    josh.addEdge("created", ripple, "weight", 1.0f);
    josh.addEdge("created", lop, "weight", 0.4f);
    peter.addEdge("created", lop, "weight", 0.2f);

    GraphTraversalSource g = graph.traversal();
    Vertex fromNode = g.V().has("name", "marko").next();
    Vertex toNode = g.V().has("name", "peter").next();
    ArrayList list = new ArrayList();
    g.V(fromNode).repeat(both().simplePath()).until(is(toNode)).limit(1).path().fill(list);
    LOGGER.info(list.toString());
    System.exit(0);
}
 
Example 9
Project: incubator-atlas   File: Titan1GraphDatabase.java   Source Code and License 6 votes vote down vote up
public static TitanGraph getGraphInstance() {
    if (graphInstance == null) {
        synchronized (Titan1GraphDatabase.class) {
            if (graphInstance == null) {
                Configuration config;
                try {
                    config = getConfiguration();
                } catch (AtlasException e) {
                    throw new RuntimeException(e);
                }

                graphInstance = TitanFactory.open(config);
                atlasGraphInstance = new Titan1Graph();
                validateIndexBackend(config);
            }
        }
    }
    return graphInstance;
}
 
Example 10
Project: incubator-atlas   File: Titan0GraphDatabase.java   Source Code and License 6 votes vote down vote up
public static TitanGraph getGraphInstance() {
    if (graphInstance == null) {
        synchronized (Titan0GraphDatabase.class) {
            if (graphInstance == null) {
                Configuration config;
                try {
                    config = getConfiguration();
                } catch (AtlasException e) {
                    throw new RuntimeException(e);
                }

                graphInstance = TitanFactory.open(config);
                atlasGraphInstance = new Titan0Graph();
                validateIndexBackend(config);
            }
        }
    }
    return graphInstance;
}
 
Example 11
Project: titan1.0.1.kafka   File: CassandraGraphTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testGraphConfigUsedByThreadBoundTx() {
    close();
    WriteConfiguration wc = getConfiguration();
    wc.set(ConfigElement.getPath(CASSANDRA_READ_CONSISTENCY), "ALL");
    wc.set(ConfigElement.getPath(CASSANDRA_WRITE_CONSISTENCY), "LOCAL_QUORUM");

    graph = (StandardTitanGraph) TitanFactory.open(wc);

    StandardTitanTx tx = (StandardTitanTx)graph.getCurrentThreadTx();
    assertEquals("ALL",
            tx.getTxHandle().getBaseTransactionConfig().getCustomOptions()
                    .get(AbstractCassandraStoreManager.CASSANDRA_READ_CONSISTENCY));
    assertEquals("LOCAL_QUORUM",
            tx.getTxHandle().getBaseTransactionConfig().getCustomOptions()
                    .get(AbstractCassandraStoreManager.CASSANDRA_WRITE_CONSISTENCY));
}
 
Example 12
Project: titan1.0.1.kafka   File: CassandraGraphTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testGraphConfigUsedByTx() {
    close();
    WriteConfiguration wc = getConfiguration();
    wc.set(ConfigElement.getPath(CASSANDRA_READ_CONSISTENCY), "TWO");
    wc.set(ConfigElement.getPath(CASSANDRA_WRITE_CONSISTENCY), "THREE");

    graph = (StandardTitanGraph) TitanFactory.open(wc);

    StandardTitanTx tx = (StandardTitanTx)graph.newTransaction();
    assertEquals("TWO",
            tx.getTxHandle().getBaseTransactionConfig().getCustomOptions()
                    .get(AbstractCassandraStoreManager.CASSANDRA_READ_CONSISTENCY));
    assertEquals("THREE",
            tx.getTxHandle().getBaseTransactionConfig().getCustomOptions()
                    .get(AbstractCassandraStoreManager.CASSANDRA_WRITE_CONSISTENCY));
    tx.rollback();
}
 
Example 13
Project: titan1.0.1.kafka   File: CassandraGraphTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testCustomConfigUsedByTx() {
    close();
    WriteConfiguration wc = getConfiguration();
    wc.set(ConfigElement.getPath(CASSANDRA_READ_CONSISTENCY), "ALL");
    wc.set(ConfigElement.getPath(CASSANDRA_WRITE_CONSISTENCY), "ALL");

    graph = (StandardTitanGraph) TitanFactory.open(wc);

    StandardTitanTx tx = (StandardTitanTx)graph.buildTransaction()
            .customOption(ConfigElement.getPath(CASSANDRA_READ_CONSISTENCY), "ONE")
            .customOption(ConfigElement.getPath(CASSANDRA_WRITE_CONSISTENCY), "TWO").start();

    assertEquals("ONE",
            tx.getTxHandle().getBaseTransactionConfig().getCustomOptions()
                    .get(AbstractCassandraStoreManager.CASSANDRA_READ_CONSISTENCY));
    assertEquals("TWO",
            tx.getTxHandle().getBaseTransactionConfig().getCustomOptions()
                    .get(AbstractCassandraStoreManager.CASSANDRA_WRITE_CONSISTENCY));
    tx.rollback();
}
 
Example 14
Project: titan1.0.1.kafka   File: ElasticSearchConfigTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testTitanFactoryBuilder()
{
    String baseDir = Joiner.on(File.separator).join("target", "es", "titanfactory_jvmlocal_ext");
    TitanFactory.Builder builder = TitanFactory.build();
    builder.set("storage.backend", "inmemory");
    builder.set("index." + INDEX_NAME + ".elasticsearch.interface", "NODE");
    builder.set("index." + INDEX_NAME + ".elasticsearch.ext.node.data", "true");
    builder.set("index." + INDEX_NAME + ".elasticsearch.ext.node.client", "false");
    builder.set("index." + INDEX_NAME + ".elasticsearch.ext.node.local", "true");
    builder.set("index." + INDEX_NAME + ".elasticsearch.ext.path.data", baseDir + File.separator + "data");
    builder.set("index." + INDEX_NAME + ".elasticsearch.ext.path.work", baseDir + File.separator + "work");
    builder.set("index." + INDEX_NAME + ".elasticsearch.ext.path.logs", baseDir + File.separator + "logs");
    TitanGraph graph = builder.open(); // Must not throw an exception
    assertTrue(graph.isOpen());
    graph.close();
}
 
Example 15
Project: titan0.5.4-hbase1.1.1-custom   File: CassandraGraphTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testGraphConfigUsedByThreadBoundTx() {
    close();
    WriteConfiguration wc = getConfiguration();
    wc.set(ConfigElement.getPath(CASSANDRA_READ_CONSISTENCY), "ALL");
    wc.set(ConfigElement.getPath(CASSANDRA_WRITE_CONSISTENCY), "LOCAL_QUORUM");

    graph = (StandardTitanGraph) TitanFactory.open(wc);

    StandardTitanTx tx = (StandardTitanTx)graph.getCurrentThreadTx();
    assertEquals("ALL",
            tx.getTxHandle().getBaseTransactionConfig().getCustomOptions()
                    .get(AbstractCassandraStoreManager.CASSANDRA_READ_CONSISTENCY));
    assertEquals("LOCAL_QUORUM",
            tx.getTxHandle().getBaseTransactionConfig().getCustomOptions()
                    .get(AbstractCassandraStoreManager.CASSANDRA_WRITE_CONSISTENCY));
}
 
Example 16
Project: titan0.5.4-hbase1.1.1-custom   File: CassandraGraphTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testGraphConfigUsedByTx() {
    close();
    WriteConfiguration wc = getConfiguration();
    wc.set(ConfigElement.getPath(CASSANDRA_READ_CONSISTENCY), "TWO");
    wc.set(ConfigElement.getPath(CASSANDRA_WRITE_CONSISTENCY), "THREE");

    graph = (StandardTitanGraph) TitanFactory.open(wc);

    StandardTitanTx tx = (StandardTitanTx)graph.newTransaction();
    assertEquals("TWO",
            tx.getTxHandle().getBaseTransactionConfig().getCustomOptions()
                    .get(AbstractCassandraStoreManager.CASSANDRA_READ_CONSISTENCY));
    assertEquals("THREE",
            tx.getTxHandle().getBaseTransactionConfig().getCustomOptions()
                    .get(AbstractCassandraStoreManager.CASSANDRA_WRITE_CONSISTENCY));
    tx.rollback();
}
 
Example 17
Project: titan0.5.4-hbase1.1.1-custom   File: CassandraGraphTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testCustomConfigUsedByTx() {
    close();
    WriteConfiguration wc = getConfiguration();
    wc.set(ConfigElement.getPath(CASSANDRA_READ_CONSISTENCY), "ALL");
    wc.set(ConfigElement.getPath(CASSANDRA_WRITE_CONSISTENCY), "ALL");

    graph = (StandardTitanGraph) TitanFactory.open(wc);

    StandardTitanTx tx = (StandardTitanTx)graph.buildTransaction()
            .setCustomOption(ConfigElement.getPath(CASSANDRA_READ_CONSISTENCY), "ONE")
            .setCustomOption(ConfigElement.getPath(CASSANDRA_WRITE_CONSISTENCY), "TWO").start();

    assertEquals("ONE",
            tx.getTxHandle().getBaseTransactionConfig().getCustomOptions()
                    .get(AbstractCassandraStoreManager.CASSANDRA_READ_CONSISTENCY));
    assertEquals("TWO",
            tx.getTxHandle().getBaseTransactionConfig().getCustomOptions()
                    .get(AbstractCassandraStoreManager.CASSANDRA_WRITE_CONSISTENCY));
    tx.rollback();
}
 
Example 18
Project: titan0.5.4-hbase1.1.1-custom   File: TestBed.java   Source Code and License 6 votes vote down vote up
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();
}
 
Example 19
Project: titan0.5.4-hbase1.1.1-custom   File: GraphGenerator.java   Source Code and License 6 votes vote down vote up
public static void main(String args[]) throws IOException {
    if (4 != args.length) {
        System.err.println("Usage: GraphGenerator titanproperties vertexcount edgecount outfile");
        System.exit(1);
    }
    int i = 0;
    String c = args[i++];
    int v = Integer.valueOf(args[i++]);
    int e = Integer.valueOf(args[i++]);
    String o = args[i++];
    Schema s = new Schema.Builder(v, e).build();
    TitanGraph graph = TitanFactory.open(c);
    new GraphGenerator(s).generateTypesAndData(graph);
    OutputStream out = new GZIPOutputStream(new FileOutputStream(o));
    GraphGenerator.writeData(graph, out);
    out.close();
    graph.shutdown();
    System.exit(0);
}
 
Example 20
Project: titan0.5.4-hbase1.1.1-custom   File: TitanSchemaAwareMapper.java   Source Code and License 6 votes vote down vote up
@Override
protected void setup(Context context) throws IOException, InterruptedException {
    super.setup(context);

    // Catch any exceptions, log a warning, and allow the subclass to continue even if schema loading failed
    try {
        ModifiableHadoopConfiguration faunusConf =
                ModifiableHadoopConfiguration.of(DEFAULT_COMPAT.getContextConfiguration(context));

        if (faunusConf.get(TitanHadoopConfiguration.OUTPUT_TITAN_TYPE_CHECKING)) {
            TitanGraph g = TitanFactory.open(faunusConf.getOutputConf());
            FaunusSchemaManager.getTypeManager(null).setSchemaProvider(new SchemaContainer(g));
            log.info("Loaded schema associated with {}", g);
        } else {
            log.debug("Titan schema checking is disabled");
        }
    } catch (Throwable t) {
        log.warn("Unable to load Titan schema", t);
    }
}
 
Example 21
Project: titan0.5.4-hbase1.1.1-custom   File: TitanIndexRepairMapper.java   Source Code and License 6 votes vote down vote up
@Override
public void setup(
        final Mapper<NullWritable, FaunusVertex, NullWritable, NullWritable>.Context context) throws IOException {
    Configuration hadoopConf = DEFAULT_COMPAT.getContextConfiguration(context);
    ModifiableHadoopConfiguration faunusConf = ModifiableHadoopConfiguration.of(hadoopConf);
    BasicConfiguration titanConf = faunusConf.getOutputConf();
    indexName = faunusConf.get(TitanHadoopConfiguration.INDEX_NAME);
    indexType = faunusConf.get(TitanHadoopConfiguration.INDEX_TYPE);

    try {
        Preconditions.checkNotNull(indexName, "Need to provide at least an index name for re-index job");
        log.info("Read index information: name={} type={}", indexName, indexType);
        graph = (StandardTitanGraph)TitanFactory.open(titanConf);
        SchemaContainer schema = new SchemaContainer(graph);
        FaunusSchemaManager typeManager = FaunusSchemaManager.getTypeManager(titanConf);
        typeManager.setSchemaProvider(schema);
        log.info("Opened graph {}", graph);
        mgmt = (ManagementSystem) graph.getManagementSystem();
        validateIndexStatus();
    } catch (final Exception e) {
        if (null != mgmt && mgmt.isOpen())
            mgmt.rollback();
        DEFAULT_COMPAT.incrementContextCounter(context, Counters.FAILED_TRANSACTIONS, 1L);
        throw new IOException(e.getMessage(), e);
    }
}
 
Example 22
Project: titan0.5.4-hbase1.1.1-custom   File: TitanCassandraInputFormatTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testCanReadListValuedProperty() throws Exception {
    TitanGraph tg = TitanFactory.open(getTitanConfiguration());

    TitanManagement mgmt = tg.getManagementSystem();
    mgmt.makePropertyKey("email").dataType(String.class).cardinality(com.thinkaurelius.titan.core.Cardinality.LIST).make();
    mgmt.commit();
    tg.commit();

    TitanVertex v = tg.addVertex();
    v.addProperty("email", "one");
    v.addProperty("email", "two");
    tg.commit();

    Configuration c = new Configuration();
    c.set("titan.hadoop.input.format", "com.thinkaurelius.titan.hadoop.formats.cassandra.TitanCassandraInputFormat");
    c.set("titan.hadoop.input.conf.storage.backend", "cassandrathrift");
    c.set("titan.hadoop.input.conf.storage.cassandra.keyspace", KEYSPACE_NAME);
    c.set("titan.hadoop.sideeffect.format", "org.apache.hadoop.mapreduce.lib.output.TextOutputFormat");
    c.set("titan.hadoop.output.format", "com.thinkaurelius.titan.hadoop.formats.graphson.GraphSONOutputFormat");
    c.set("cassandra.input.partitioner.class", "org.apache.cassandra.dht.Murmur3Partitioner");

    HadoopGraph hg = new HadoopGraph(c);

    assertEquals(0, new HadoopPipeline(hg).V().map().submit());
}
 
Example 23
Project: titan-web-example   File: PopulateDB.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    Configuration conf = new PropertiesConfiguration(TitanGraphFactory.PROPS_PATH);

    TitanGraph g = TitanFactory.open(conf);

    // Uncomment the following if your graph is already populated and you want to clear it out first.
    // g.close();
    // TitanCleanup.clear(g);
    // g = TitanFactory.open(conf);

    // Interested in the source?
    // https://github.com/thinkaurelius/titan/blob/titan05/titan-core/src/main/java/com/thinkaurelius/titan/example/GraphOfTheGodsFactory.java
    GraphOfTheGodsFactory.load(g);
    g.close();
    System.out.println("Success.");
}
 
Example 24
Project: extended-objects-titan   File: TitanCassandraStore.java   Source Code and License 6 votes vote down vote up
@Override
   public void init(Map<Class<?>, TypeMetadata> registeredMetadata) {
logger.info("Initializing eXtended Objects for Titan on Cassandra...");
Configuration configuration = new BaseConfiguration();
configuration.setProperty("storage.backend", "cassandra");
configuration.setProperty("storage.hostname", host);
if (port > 0) {
    configuration.setProperty("storage.port", port);
}
if (keyspace != null) {
    configuration.setProperty("storage.cassandra.keyspace", keyspace);
}
titanGraph = TitanFactory.open(configuration);
try {
    checkAndInitializeDiscriminatorProperties(registeredMetadata);
    checkAndInitializePropertyIndizes(registeredMetadata);
} finally {
    titanGraph.commit();
}
   }
 
Example 25
Project: antiquity   File: TitanTxLongVersionedGraphTest.java   Source Code and License 6 votes vote down vote up
@Override
protected ActiveVersionedGraph<?, Long> generateGraph() {
    File f = new File("/tmp/testgraph");
    if (f.exists()) {
        if (f.isDirectory()) {
            try {
                FileUtils.deleteDirectory(f);
            } catch (IOException e) {
                throw new IllegalStateException(e);
            }
        } else {
            f.delete();
        }

    }

    Configuration c = new BaseConfiguration();
    c.addProperty("storage.directory","/tmp/testgraph");
    TitanGraph g = TitanFactory.open(c);

    return new ActiveVersionedGraph.ActiveVersionedTransactionalGraphBuilder<TitanGraph, Long>(g, new LongGraphIdentifierBehavior())
            .init(true).conf(null).build();
}
 
Example 26
Project: keti   File: GraphSubjectRepositoryTest.java   Source Code and License 5 votes vote down vote up
@BeforeClass
public void setup() throws Exception {
    this.subjectRepository = new GraphSubjectRepository();
    Graph graph = TitanFactory.build().set("storage.backend", "inmemory").open();
    GraphConfig.createSchemaElements(graph);
    this.graphTraversalSource = graph.traversal();
    this.subjectRepository.setGraphTraversal(this.graphTraversalSource);
}
 
Example 27
Project: marauder   File: MarauderTitanSink.java   Source Code and License 5 votes vote down vote up
@Override
	public void configure(Context context) {
		Configuration conf = new BaseConfiguration();
		conf.setProperty("storage.backend","hbase");
		conf.setProperty("storage.hostname",
		context.getString("servers", "192.168.1.20"));
//		conf.setProperty("storage.index.t.backend", "lucene");
//		conf.setProperty("storage.index.t.directory", "/tmp/index");
		conf.setProperty("storage.batch-loading", "true");
		batchSize = context.getInteger("batchSize", 1000);
		g = TitanFactory.open(conf);
		g.makeKey("t").dataType(String.class).indexed(Vertex.class).make();
		g.makeKey("o").dataType(Integer.class).indexed(Vertex.class).make();
		g.makeKey("s").dataType(Long.class).indexed(Vertex.class).make();
		g.makeKey("n").dataType(String.class).indexed(Vertex.class).make();
		g.makeLabel("dil").unidirected().manyToMany().make();
		g.makeLabel("sil").unidirected().manyToMany().make();
		g.makeLabel("dpl").unidirected().manyToMany().make();
		g.makeLabel("spl").unidirected().manyToMany().make();
		g.makeLabel("isl").unidirected().manyToMany().make();
		g.makeLabel("hl").unidirected().manyToMany().make();
		g.makeLabel("evl").unidirected().manyToMany().make();
		g.makeLabel("il").unidirected().manyToMany().make();
		g.makeLabel("tl").unidirected().manyToMany().make();
		g.makeLabel("gil").unidirected().manyToMany().make();
		g.commit();
	}
 
Example 28
Project: titan1withtp3.1   File: AbstractTitanGraphProvider.java   Source Code and License 5 votes vote down vote up
@Override
public Map<String, Object> getBaseConfiguration(String graphName, Class<?> test, String testMethodName, final LoadGraphWith.GraphData loadGraphWith) {
    ModifiableConfiguration conf = getTitanConfiguration(graphName, test, testMethodName);
    conf.set(GraphDatabaseConfiguration.COMPUTER_RESULT_MODE, "persist");
    conf.set(GraphDatabaseConfiguration.AUTO_TYPE, "tp3");
    Map<String, Object> result = new HashMap<>();
    conf.getAll().entrySet().stream().forEach(e -> result.put(ConfigElement.getPath(e.getKey().element, e.getKey().umbrellaElements), e.getValue()));
    result.put(Graph.GRAPH, TitanFactory.class.getName());
    return result;
}
 
Example 29
Project: titan1withtp3.1   File: VertexIDAssignerTest.java   Source Code and License 5 votes vote down vote up
private static TitanGraph getInMemoryGraph() {
    ModifiableConfiguration config = GraphDatabaseConfiguration.buildGraphConfiguration();
    config.set(GraphDatabaseConfiguration.STORAGE_BACKEND, InMemoryStoreManager.class.getCanonicalName());
    config.set(GraphDatabaseConfiguration.IDS_FLUSH, false);
    config.set(GraphDatabaseConfiguration.IDAUTHORITY_WAIT, Duration.ofMillis(1L));
    return TitanFactory.open(config);
}
 
Example 30
Project: titan1withtp3.1   File: TinkerpopFeaturesTest.java   Source Code and License 5 votes vote down vote up
public TitanGraph open(boolean useVertexIdSetting)
{
    TitanFactory.Builder builder = TitanFactory.build();
    builder.set("storage.backend", "inmemory");
    builder.set("graph.set-vertex-id", useVertexIdSetting);
    return builder.open();
}
 
Example 31
Project: titan1withtp3.1   File: HadoopVertexScanMapper.java   Source Code and License 5 votes vote down vote up
@Override
protected void setup(Context context) throws IOException, InterruptedException {
    /* Don't call super implementation super.setup(context); */
    org.apache.hadoop.conf.Configuration hadoopConf = DEFAULT_COMPAT.getContextConfiguration(context);
    ModifiableHadoopConfiguration scanConf = ModifiableHadoopConfiguration.of(TitanHadoopConfiguration.MAPRED_NS, hadoopConf);
    VertexScanJob vertexScan = getVertexScanJob(scanConf);
    ModifiableConfiguration graphConf = getTitanConfiguration(context);
    TitanGraph graph = TitanFactory.open(graphConf);
    job = VertexJobConverter.convert(graph, vertexScan);
    metrics = new HadoopContextScanMetrics(context);
    finishSetup(scanConf, graphConf);
}
 
Example 32
Project: titan1withtp3.1   File: GraphOfTheGodsFactory.java   Source Code and License 5 votes vote down vote up
public static TitanGraph create(final String directory) {
    TitanFactory.Builder config = TitanFactory.build();
    config.set("storage.backend", "berkeleyje");
    config.set("storage.directory", directory);
    config.set("index." + INDEX_NAME + ".backend", "elasticsearch");
    config.set("index." + INDEX_NAME + ".directory", directory + File.separator + "es");
    config.set("index." + INDEX_NAME + ".elasticsearch.local-mode", true);
    config.set("index." + INDEX_NAME + ".elasticsearch.client-only", false);

    TitanGraph graph = config.open();
    GraphOfTheGodsFactory.load(graph);
    return graph;
}
 
Example 33
Project: ldbc-snb-impls   File: TitanDbConnectionState.java   Source Code and License 5 votes vote down vote up
public TitanDbConnectionState(Map<String, String> props) {
  BaseConfiguration config = new BaseConfiguration();
  config.setDelimiterParsingDisabled(true);

  /*
   * Extract parameters from properties map.
   */
  String cassandraLocator;
  if (props.containsKey("cassandraLocator")) {
    cassandraLocator = props.get("cassandraLocator");
  } else {
    cassandraLocator = "127.0.0.1";
  }

  String graphName;
  if (props.containsKey("graphName")) {
    graphName = props.get("graphName");
  } else {
    graphName = "default";
  }
  
  config.setProperty("storage.backend", "cassandra");
  config.setProperty("storage.hostname", cassandraLocator);
  config.setProperty("storage.cassandra.keyspace", graphName);

  client = TitanFactory.open(config);
}
 
Example 34
Project: simmo-stream-manager   File: TitanGraphDbStorage.java   Source Code and License 5 votes vote down vote up
@Override
public boolean open() {
	BaseConfiguration conf = new BaseConfiguration();
	conf.setProperty("storage.backend", storageBackend);
	conf.setProperty("storage.tablename", storageTableName);
	titanGraph = TitanFactory.open(conf);
	titanGraph.makeKey(vertexUserId).dataType(String.class).indexed(Vertex.class).make();
	titanGraph.makeLabel(edgeMentions).make();
	titanGraph.makeLabel(edgeReTweets).make();
	titanGraph.commit();
	return true;
}
 
Example 35
Project: titan1.0.1.kafka   File: AbstractTitanGraphProvider.java   Source Code and License 5 votes vote down vote up
@Override
public Map<String, Object> getBaseConfiguration(String graphName, Class<?> test, String testMethodName, final LoadGraphWith.GraphData loadGraphWith) {
    ModifiableConfiguration conf = getTitanConfiguration(graphName, test, testMethodName);
    conf.set(GraphDatabaseConfiguration.COMPUTER_RESULT_MODE, "persist");
    conf.set(GraphDatabaseConfiguration.AUTO_TYPE, "tp3");
    Map<String, Object> result = new HashMap<>();
    conf.getAll().entrySet().stream().forEach(e -> result.put(ConfigElement.getPath(e.getKey().element, e.getKey().umbrellaElements), e.getValue()));
    result.put(Graph.GRAPH, TitanFactory.class.getName());
    return result;
}
 
Example 36
Project: titan1.0.1.kafka   File: VertexIDAssignerTest.java   Source Code and License 5 votes vote down vote up
private static TitanGraph getInMemoryGraph() {
    ModifiableConfiguration config = GraphDatabaseConfiguration.buildGraphConfiguration();
    config.set(GraphDatabaseConfiguration.STORAGE_BACKEND, InMemoryStoreManager.class.getCanonicalName());
    config.set(GraphDatabaseConfiguration.IDS_FLUSH, false);
    config.set(GraphDatabaseConfiguration.IDAUTHORITY_WAIT, Duration.ofMillis(1L));
    return TitanFactory.open(config);
}
 
Example 37
Project: titan1.0.1.kafka   File: TinkerpopFeaturesTest.java   Source Code and License 5 votes vote down vote up
public TitanGraph open(boolean useVertexIdSetting)
{
    TitanFactory.Builder builder = TitanFactory.build();
    builder.set("storage.backend", "inmemory");
    builder.set("graph.set-vertex-id", useVertexIdSetting);
    return builder.open();
}
 
Example 38
Project: titan1.0.1.kafka   File: HadoopVertexScanMapper.java   Source Code and License 5 votes vote down vote up
@Override
protected void setup(Context context) throws IOException, InterruptedException {
    /* Don't call super implementation super.setup(context); */
    org.apache.hadoop.conf.Configuration hadoopConf = DEFAULT_COMPAT.getContextConfiguration(context);
    ModifiableHadoopConfiguration scanConf = ModifiableHadoopConfiguration.of(TitanHadoopConfiguration.MAPRED_NS, hadoopConf);
    VertexScanJob vertexScan = getVertexScanJob(scanConf);
    ModifiableConfiguration graphConf = getTitanConfiguration(context);
    TitanGraph graph = TitanFactory.open(graphConf);
    job = VertexJobConverter.convert(graph, vertexScan);
    metrics = new HadoopContextScanMetrics(context);
    finishSetup(scanConf, graphConf);
}
 
Example 39
Project: titan1.0.1.kafka   File: GraphOfTheGodsFactory.java   Source Code and License 5 votes vote down vote up
public static TitanGraph create(final String directory) {
    TitanFactory.Builder config = TitanFactory.build();
    config.set("storage.backend", "berkeleyje");
    config.set("storage.directory", directory);
    config.set("index." + INDEX_NAME + ".backend", "elasticsearch");
    config.set("index." + INDEX_NAME + ".directory", directory + File.separator + "es");
    config.set("index." + INDEX_NAME + ".elasticsearch.local-mode", true);
    config.set("index." + INDEX_NAME + ".elasticsearch.client-only", false);

    TitanGraph graph = config.open();
    GraphOfTheGodsFactory.load(graph);
    return graph;
}
 
Example 40
Project: titan0.5.4-hbase1.1.1-custom   File: VertexIDAssignerTest.java   Source Code and License 5 votes vote down vote up
private static TitanGraph getInMemoryGraph() {
    ModifiableConfiguration config = GraphDatabaseConfiguration.buildConfiguration();
    config.set(GraphDatabaseConfiguration.STORAGE_BACKEND, InMemoryStoreManager.class.getCanonicalName());
    config.set(GraphDatabaseConfiguration.IDS_FLUSH, false);
    config.set(GraphDatabaseConfiguration.IDAUTHORITY_WAIT, new StandardDuration(1L, TimeUnit.MILLISECONDS));
    return TitanFactory.open(config);
}
 
Example 41
Project: titan0.5.4-hbase1.1.1-custom   File: TitanGraphConfiguration.java   Source Code and License 5 votes vote down vote up
@Override
public Graph configureGraphInstance(final GraphConfigurationContext context) throws GraphConfigurationException {
    log.debug("Calling TitanFactory.open({})", context);
    final Graph g = TitanFactory.open(convertConfiguration(context));
    log.debug("Returning new graph {}", g);
    return g;
}
 
Example 42
Project: peapod   File: TitanSuite.java   Source Code and License 5 votes vote down vote up
@BeforeClass
public static void setGraphProvider() throws IOException {
    GraphTest.graphProvider = new GraphProvider() {
        public Graph getGraph() throws IOException {
            TitanGraph graph = TitanFactory.build().set("storage.backend", "inmemory").open();
            TitanManagement management = graph.openManagement();
            management.makePropertyKey("location").dataType(String.class).cardinality(Cardinality.LIST).make();
            management.makePropertyKey("firstName").dataType(String.class).cardinality(Cardinality.LIST).make();
            management.commit();
            return graph;
        }
    };

}
 
Example 43
Project: marmotta-titan   File: TitanStoreProvider.java   Source Code and License 5 votes vote down vote up
/**
 * Create a TitanGraph from the configuration
 *
 * @return TitanGraph
 */
public TitanGraph createTitanGraph() {
	Configuration conf = new BaseConfiguration();
	List<String> titanConf = configurationService.listConfigurationKeys("titan");
	for (String key : titanConf) {
		String titanKey = key.replaceFirst("^titan\\.", "");
		conf.setProperty(titanKey, configurationService.getStringConfiguration(key));
	}

	return TitanFactory.open(conf);
}
 
Example 44
Project: ldbc_snb_implementations   File: TitanFTMDb.java   Source Code and License 5 votes vote down vote up
BasicClient(String pathToConfFile) {
    //Shifting all ids by mult to accomodate vertex type id suffixes
    mult = (int) (Math.log10((double) s.getVertexTypes().size()) + 1);
    //Using IDgraph to wrap titan graph which doesn't allow user vertex defined vertex IDs
    logger.debug("pathtoConfFile: {}",pathToConfFile);
    TitanGraph base = TitanFactory.open(pathToConfFile);
    g = new IdGraph<>(base, true, false);
}
 
Example 45
Project: marmotta   File: TitanLoaderHandler.java   Source Code and License 5 votes vote down vote up
/**
 * Initialise the handler, performing any initialisation steps that are necessary before bulk importing can
 * start (e.g. dropping indexes or establishing a connection).
 *
 * @throws org.openrdf.rio.RDFHandlerException
 */
@Override
public void initialise() throws RDFHandlerException {
    log.info("Initializing new Titan Graph Store (backend: {})", configuration.getString("storage.backend"));

    handler = new TitanRDFHandler(TitanFactory.open(configuration), configuration.getString("storage.indexes","p,c,pc"));
 }
 
Example 46
Project: marmotta   File: TitanStoreProvider.java   Source Code and License 5 votes vote down vote up
/**
 * Create a TitanGraph from the configuration
 *
 * @return TitanGraph
 */
public TitanGraph createTitanGraph() {
	Configuration conf = new BaseConfiguration();
	List<String> titanConf = configurationService.listConfigurationKeys("titan");
	for (String key : titanConf) {
		String titanKey = key.replaceFirst("^titan\\.", "");
		conf.setProperty(titanKey, configurationService.getStringConfiguration(key));
	}

	return TitanFactory.open(conf);
}
 
Example 47
Project: titan-web-example   File: TitanGraphFactory.java   Source Code and License 5 votes vote down vote up
@PostConstruct
public void init() {
    try {
        logger.info("Titan Properties Path: {}", PROPS_PATH);
        Configuration conf = new PropertiesConfiguration(PROPS_PATH);
        g = TitanFactory.open(conf);
        logger.info("Titan graph loaded successfully.");
    } catch (ConfigurationException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 48
Project: js-parser   File: App.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    String rootPath = args[0];
    String outPath = args[1];

    // Railo config
    File root = new File(rootPath);

    // Create graph
    Configuration conf = new BaseConfiguration();
    conf.setProperty("storage.backend", "inmemory");
    TitanGraph graph = TitanFactory.open(conf);
    Map<String,Vertex> map = new HashMap<String, Vertex>();

    // Scan
    new FileScanner(graph, map).scan(root);

    // Write
    FileOutputStream out = null;
    try {
        out = new FileOutputStream(new File(outPath));
        GraphMLWriter.outputGraph(graph, out);
    } catch (Exception ex) {
        if(out != null) {
            out.close();
        }
        throw ex;
    }
    graph.shutdown();
}
 
Example 49
Project: titan-experimental   File: PersistitBlueprintsTest.java   Source Code and License 5 votes vote down vote up
@Override
public Graph generateGraph(final String subdir) {
    String dir = PersistitStorageSetup.getHomeDir() + "/" + subdir;
    Configuration config= new BaseConfiguration();
    config.subset(STORAGE_NAMESPACE).addProperty(STORAGE_DIRECTORY_KEY, dir);
    config.subset(STORAGE_NAMESPACE).addProperty(STORAGE_BACKEND_KEY, "persistit");
    Graph g = TitanFactory.open(config);
    synchronized (openGraphs) {
        openGraphs.put(dir, g);
    }
    return g;
}
 
Example 50
Project: titan-cassandra-elasticsearch-index   File: TitanStart.java   Source Code and License 4 votes vote down vote up
public static void main(String[] args) throws Exception {

		Configuration conf = new PropertiesConfiguration( getRelativeResourcePath( "titan-cassandra-es.properties" ) );
		// start elastic search on startup
		Node node = new NodeBuilder().node();
		
		TitanGraph graph = TitanFactory.open(conf);
		/* Comment if you do not want to reload the graph every time */
		graph.close();
		TitanCleanup.clear(graph);
		graph = TitanFactory.open(conf);
		GraphOfTheGodsFactory.load(graph);
		/* graph loaded  */
		
		// create own indexes
		TitanManagement mgmt = graph.openManagement();
		PropertyKey name = mgmt.getPropertyKey("name");
		PropertyKey age = mgmt.getPropertyKey("age");
		mgmt.buildIndex( "byNameComposite", Vertex.class ).addKey(name).buildCompositeIndex();
		// index consisting of multiple properties
		mgmt.buildIndex( "byNameAndAgeComposite", Vertex.class ).addKey(name).addKey(age).buildCompositeIndex();
		mgmt.commit();
		
		// wait for the index to become available
		ManagementSystem.awaitGraphIndexStatus(graph, "byNameComposite").call();
		ManagementSystem.awaitGraphIndexStatus(graph, "byNameAndAgeComposite").call();
		
		// create new vertex
		Vertex me = graph.addVertex("theOneAndOnly");
		me.property( "name", "me" );
		me.property( "age", 1 );
		graph.tx().commit();
		System.out.println("Created the one and only!");
		
		// re index the existing data (not required, just for demo purposes)
		mgmt = graph.openManagement();
		mgmt.updateIndex( mgmt.getGraphIndex("byNameComposite"), SchemaAction.REINDEX ).get();
		mgmt.updateIndex( mgmt.getGraphIndex("byNameAndAgeComposite"), SchemaAction.REINDEX ).get();
		mgmt.commit();
		
		GraphTraversalSource g = graph.traversal();
		GremlinPipeline<GraphTraversal<?, ?>, ?> pipe = new GremlinPipeline();
		
		// read our new vertex
		pipe.start( g.V().has( "name", "me" ) );	
		Vertex v = (Vertex)pipe.next();
		System.out.println();
		System.out.println( "Label: " + v.label() );
		System.out.println( "Name: " + v.property("name").value() );
		System.out.println( "Age: " + v.property("age").value() );
		System.out.println();
		
		// read different vertex
		pipe.start( g.V().has( "name", "hercules" ) );	
		Vertex herclues = (Vertex)pipe.next();
		System.out.println( "Label: " + herclues.label() );
		System.out.println( "Name: " + herclues.property("name").value() );
		System.out.println( "Age: " + herclues.property("age").value() );
		
		// print some edges
		Iterator<Edge> it = herclues.edges( Direction.OUT );
		while( it.hasNext() ) {
			Edge e = it.next();
			System.out.println( "Out: " + e.label()  + " --> " + e.inVertex().property("name").value() );
		}
		System.out.println();
		
		// close graph
		graph.close();
		// close elastic search on shutdown
		node.close();
		
		System.exit(0);
	}
 
Example 51
Project: keti   File: GraphResourceRepositoryTest.java   Source Code and License 4 votes vote down vote up
private void setupTitanGraph() throws InterruptedException, ExecutionException {
    Graph graph = TitanFactory.build().set("storage.backend", "inmemory").open();
    GraphConfig.createSchemaElements(graph);
    this.graphTraversalSource = graph.traversal();
    this.dropAllResources();
}
 
Example 52
Project: titan1withtp3.1   File: StorageSetup.java   Source Code and License 4 votes vote down vote up
public static TitanGraph getInMemoryGraph() {
    return TitanFactory.open(getInMemoryConfiguration());
}
 
Example 53
Project: titan1withtp3.1   File: TitanGraphTest.java   Source Code and License 4 votes vote down vote up
private <T> void setAndCheckGraphOption(ConfigOption<T> opt, ConfigOption.Type requiredType, T firstValue, T secondValue) {
    // Sanity check: make sure the Type of the configoption is what we expect
    Preconditions.checkState(opt.getType().equals(requiredType));
    final EnumSet<ConfigOption.Type> allowedTypes =
            EnumSet.of(ConfigOption.Type.GLOBAL,
                    ConfigOption.Type.GLOBAL_OFFLINE,
                    ConfigOption.Type.MASKABLE);
    Preconditions.checkState(allowedTypes.contains(opt.getType()));

    // Sanity check: it's kind of pointless for the first and second values to be identical
    Preconditions.checkArgument(!firstValue.equals(secondValue));

    // Get full string path of config option
    final String path = ConfigElement.getPath(opt);

    // Set and check initial value before and after database restart
    mgmt.set(path, firstValue);
    assertEquals(firstValue.toString(), mgmt.get(path));
    // Close open tx first.  This is specific to BDB + GLOBAL_OFFLINE.
    // Basically: the BDB store manager throws a fit if shutdown is called
    // with one or more transactions still open, and GLOBAL_OFFLINE calls
    // shutdown on our behalf when we commit this change.
    tx.rollback();
    mgmt.commit();
    clopen();
    // Close tx again following clopen
    tx.rollback();
    assertEquals(firstValue.toString(), mgmt.get(path));

    // Set and check updated value before and after database restart
    mgmt.set(path, secondValue);
    assertEquals(secondValue.toString(), mgmt.get(path));
    mgmt.commit();
    clopen();
    tx.rollback();
    assertEquals(secondValue.toString(), mgmt.get(path));

    // Open a separate graph "g2"
    TitanGraph g2 = TitanFactory.open(config);
    TitanManagement m2 = g2.openManagement();
    assertEquals(secondValue.toString(), m2.get(path));

    // GLOBAL_OFFLINE options should be unmodifiable with g2 open
    if (opt.getType().equals(ConfigOption.Type.GLOBAL_OFFLINE)) {
        try {
            mgmt.set(path, firstValue);
            mgmt.commit();
            fail("Option " + path + " with type " + ConfigOption.Type.GLOBAL_OFFLINE + " should not be modifiable with concurrent instances");
        } catch (RuntimeException e) {
            log.debug("Caught expected exception", e);
        }
        assertEquals(secondValue.toString(), mgmt.get(path));
        // GLOBAL and MASKABLE should be modifiable even with g2 open
    } else {
        mgmt.set(path, firstValue);
        assertEquals(firstValue.toString(), mgmt.get(path));
        mgmt.commit();
        clopen();
        assertEquals(firstValue.toString(), mgmt.get(path));
    }

    m2.rollback();
    g2.close();
}
 
Example 54
Project: titan1withtp3.1   File: TitanIndexTest.java   Source Code and License 4 votes vote down vote up
@Category({BrittleTests.class})
    @Test
    public void testIndexReplay() throws Exception {
        final TimestampProvider times = graph.getConfiguration().getTimestampProvider();
        final Instant startTime = times.getTime();
        clopen(option(SYSTEM_LOG_TRANSACTIONS), true
                , option(KCVSLog.LOG_READ_LAG_TIME, TRANSACTION_LOG), Duration.ofMillis(50)
                , option(LOG_READ_INTERVAL, TRANSACTION_LOG), Duration.ofMillis(250)
                , option(MAX_COMMIT_TIME), Duration.ofSeconds(1)
                , option(STORAGE_WRITE_WAITTIME), Duration.ofMillis(300)
                , option(TestMockIndexProvider.INDEX_BACKEND_PROXY, INDEX), readConfig.get(INDEX_BACKEND, INDEX)
                , option(INDEX_BACKEND, INDEX), TestMockIndexProvider.class.getName()
                , option(TestMockIndexProvider.INDEX_MOCK_FAILADD, INDEX), true
        );

        PropertyKey name = mgmt.makePropertyKey("name").dataType(String.class).make();
        PropertyKey age = mgmt.makePropertyKey("age").dataType(Integer.class).make();
        mgmt.buildIndex("mi", Vertex.class).addKey(name, getTextMapping()).addKey(age).buildMixedIndex(INDEX);
        finishSchema();
        Vertex vs[] = new TitanVertex[4];

        vs[0] = tx.addVertex("name", "Big Boy Bobson", "age", 55);
        newTx();
        vs[1] = tx.addVertex("name", "Long Little Lewis", "age", 35);
        vs[2] = tx.addVertex("name", "Tall Long Tiger", "age", 75);
        vs[3] = tx.addVertex("name", "Long John Don", "age", 15);
        newTx();
        vs[2] = getV(tx, vs[2]);
        vs[2].remove();
        vs[3] = getV(tx, vs[3]);
        vs[3].property(VertexProperty.Cardinality.single, "name", "Bad Boy Badsy");
        vs[3].property("age").remove();
        newTx();
        vs[0] = getV(tx, vs[0]);
        vs[0].property(VertexProperty.Cardinality.single, "age", 66);
        newTx();

        clopen();
        //Just to make sure nothing has been persisted to index
        evaluateQuery(tx.query().has("name", Text.CONTAINS, "boy"),
                ElementCategory.VERTEX, 0, new boolean[]{true, true}, "mi");
        /*
        Transaction Recovery
         */
        TransactionRecovery recovery = TitanFactory.startTransactionRecovery(graph, startTime);
        //wait
        Thread.sleep(12000L);

        recovery.shutdown();
        long[] recoveryStats = ((StandardTransactionLogProcessor) recovery).getStatistics();

        clopen();

        evaluateQuery(tx.query().has("name", Text.CONTAINS, "boy"),
                ElementCategory.VERTEX, 2, new boolean[]{true, true}, "mi");
        evaluateQuery(tx.query().has("name", Text.CONTAINS, "long"),
                ElementCategory.VERTEX, 1, new boolean[]{true, true}, "mi");
//        TitanVertex v = Iterables.getOnlyElement(tx.query().has("name",Text.CONTAINS,"long").vertices());
//        System.out.println(v.getProperty("age"));
        evaluateQuery(tx.query().has("name", Text.CONTAINS, "long").interval("age", 30, 40),
                ElementCategory.VERTEX, 1, new boolean[]{true, true}, "mi");
        evaluateQuery(tx.query().has("age", 75),
                ElementCategory.VERTEX, 0, new boolean[]{true, true}, "mi");
        evaluateQuery(tx.query().has("name", Text.CONTAINS, "boy").interval("age", 60, 70),
                ElementCategory.VERTEX, 1, new boolean[]{true, true}, "mi");
        evaluateQuery(tx.query().interval("age", 0, 100),
                ElementCategory.VERTEX, 2, new boolean[]{true, true}, "mi");


        assertEquals(1, recoveryStats[0]); //schema transaction was successful
        assertEquals(4, recoveryStats[1]); //all 4 index transaction had provoked errors in the indexing backend
    }
 
Example 55
Project: titan1withtp3.1   File: VertexListTest.java   Source Code and License 4 votes vote down vote up
@Test
public void testLists() {

    int num = 13;

    TitanGraph g = TitanFactory.open("inmemory");
    StandardTitanTx tx = (StandardTitanTx) g.newTransaction();
    VertexLongList vll = new VertexLongList(tx);
    VertexArrayList val = new VertexArrayList(tx);
    for (int i=0; i<num; i++) {
        TitanVertex v = tx.addVertex();
        vll.add(v);
        val.add(v);
    }

    assertEquals(num, Iterables.size(vll));
    assertEquals(num, Iterables.size(val));

    vll.sort();
    val.sort();
    assertTrue(vll.isSorted());
    assertTrue(val.isSorted());

    for (Iterable<TitanVertex> iterable : new Iterable[]{val,vll}) {
        Iterator<TitanVertex> iter = iterable.iterator();
        TitanVertex previous = null;
        for (int i = 0; i < num; i++) {
            TitanVertex next = iter.next();
            if (previous!=null) assertTrue(previous.longId()<next.longId());
            previous = next;
        }
        try {
            iter.next();
            fail();
        } catch (NoSuchElementException ex) {

        }
    }


    tx.commit();
    g.close();

}
 
Example 56
Project: titan1withtp3.1   File: TitanFactoryShorthandTest.java   Source Code and License 4 votes vote down vote up
@Test
public void testTitanFactoryShorthand() {
    TitanGraph g = TitanFactory.open("inmemory");
    g.close();
}
 
Example 57
Project: titan1withtp3.1   File: InMemoryConfigurationTest.java   Source Code and License 4 votes vote down vote up
public void initialize(ConfigOption option, Object value) {
    ModifiableConfiguration config = GraphDatabaseConfiguration.buildGraphConfiguration();
    config.set(GraphDatabaseConfiguration.STORAGE_BACKEND,"inmemory");
    config.set(option,value);
    graph = (StandardTitanGraph) TitanFactory.open(config);
}
 
Example 58
Project: titan1withtp3.1   File: TitanHadoopSetupImpl.java   Source Code and License 4 votes vote down vote up
public TitanHadoopSetupImpl(final Configuration config) {
    scanConf = ModifiableHadoopConfiguration.of(TitanHadoopConfiguration.MAPRED_NS, config);
    BasicConfiguration bc = scanConf.getTitanGraphConf();
    graph = (StandardTitanGraph) TitanFactory.open(bc);
    tx = (StandardTitanTx)graph.buildTransaction().readOnly().vertexCacheSize(200).start();
}
 
Example 59
Project: titan1withtp3.1   File: VertexJobConverter.java   Source Code and License 4 votes vote down vote up
public void initializeGraph(Configuration config) {
    if (!provided) {
        this.graph = (StandardTitanGraph) TitanFactory.open((BasicConfiguration) config);
    }
}
 
Example 60
Project: antioch   File: TitanService.java   Source Code and License 4 votes vote down vote up
private static Storage getStorage(AntiochConfiguration configuration) {
  titanGraph = TitanFactory.open(String.join(":", "berkeleyje", configuration.getStorageDirectory()));
  setIndexes();
  return new Storage(titanGraph);
}