Java源码示例:com.tinkerpop.blueprints.Graph

示例1
private static void copyEdge(Graph graph, Edge edge)
{
	Object id = edge.getId();
	if (graph.getEdge(id) != null)
	{
		return;
	}
	Vertex src = graph.getVertex(edge.getVertex(Direction.OUT).getId());
	Vertex dst = graph.getVertex(edge.getVertex(Direction.IN).getId());
	if (src != null && dst != null)
	{
		Edge e = GraphHelper.addEdge(graph, id, src, dst, edge.getLabel());
		if (e != null)
		{
			ElementHelper.copyProperties(edge, e);
		}
	}
}
 
示例2
@Test
public void testEdgeInputMap() throws Exception {
  final String INSTANCE_NAME = "_mapreduce_instance";
  final String TEST_TABLE_NAME = "_mapreduce_table_edgeInputMap";

  if (!System.getProperty("os.name").startsWith("Windows")) {
    Graph g = GraphFactory.open(new AccumuloGraphConfiguration().setInstanceName(INSTANCE_NAME)
        .setUser("root").setPassword("".getBytes())
        .setGraphName(TEST_TABLE_NAME).setInstanceType(InstanceType.Mock)
        .setAutoFlush(true).setCreate(true).getConfiguration());

    for (int i = 0; i < 100; i++) {
      Vertex v1 = g.addVertex(i+"");
      Vertex v2 = g.addVertex(i+"a");
      g.addEdge(null, v1, v2, "knows");
    }

    assertEquals(0, MRTester.main(new String[]{"root", "",
        TEST_TABLE_NAME, INSTANCE_NAME, "true"}));
    assertNull(e1);
    assertNull(e2);

    g.shutdown();
  }
}
 
示例3
@Test
public void testElementCacheSize() throws Exception {
  AccumuloGraphConfiguration cfg = AccumuloGraphTestUtils
      .generateGraphConfig("elementCacheSize");
  Graph graph = GraphFactory.open(cfg.getConfiguration());

  Vertex[] verts = new Vertex[10];
  for (int i = 0; i < verts.length; i++) {
    verts[i] = graph.addVertex(i);
  }

  Edge[] edges = new Edge[9];
  for (int i = 0; i < edges.length; i++) {
    edges[i] = graph.addEdge(null,
        verts[0], verts[i+1], "edge");
  }

  sizeTests(verts);
  sizeTests(edges);

  graph.shutdown();
}
 
示例4
@GET
@Path("/{id}")
@ApiOperation(value = "Get all properties of a node", response = Graph.class)
@Timed
@CacheControl(maxAge = 2, maxAgeUnit = TimeUnit.HOURS)
@Produces({MediaType.APPLICATION_JSON, CustomMediaTypes.APPLICATION_GRAPHSON,
    MediaType.APPLICATION_XML, CustomMediaTypes.APPLICATION_GRAPHML,
    CustomMediaTypes.APPLICATION_XGMML, CustomMediaTypes.TEXT_GML, CustomMediaTypes.TEXT_CSV,
    CustomMediaTypes.TEXT_TSV, CustomMediaTypes.IMAGE_JPEG, CustomMediaTypes.IMAGE_PNG})
public Object getNode(
    @ApiParam(value = DocumentationStrings.GRAPH_ID_DOC,
        required = true) @PathParam("id") String id,
    @ApiParam(value = DocumentationStrings.PROJECTION_DOC,
        required = false) @QueryParam("project") @DefaultValue("*") Set<String> projection,
    @ApiParam(value = DocumentationStrings.JSONP_DOC,
        required = false) @QueryParam("callback") String callback) {
  return getNeighbors(id, new IntParam("0"), new BooleanParam("false"), new HashSet<String>(),
      "BOTH", new BooleanParam("false"), projection, callback);
}
 
示例5
private static AbstractLayout<Vertex, Edge> getLayout(GraphJung<Graph> graph, String layoutName) {
  switch (layoutName) {
    case "KKLayout":
      return new KKLayout<>(graph);
    case "CircleLayout":
      return new CircleLayout<>(graph);
    case "FRLayout":
      return new FRLayout<>(graph);
    case "FRLayout2":
      return new FRLayout2<>(graph);
    case "ISOMLayout":
      return new ISOMLayout<>(graph);
    case "SpringLayout":
      return new SpringLayout<>(graph);
    default:
      return new KKLayout<>(graph);
  }
}
 
示例6
@Override
public void writeTo(Graph data, Class<?> type, Type genericType, Annotation[] annotations,
    MediaType mediaType, MultivaluedMap<String, Object> headers, OutputStream out) throws IOException {
  Integer width = Integer.parseInt(Optional.ofNullable(request.getParameter("width")).orElse(DEFAULT_WIDTH));
  Integer height = Integer.parseInt(Optional.ofNullable(request.getParameter("height")).orElse(DEFAULT_HEIGHT));
  String layoutName = Optional.ofNullable(request.getParameter("layout")).orElse(DEFAULT_LAYOUT);

  GraphJung<Graph> graph = new GraphJung<Graph>(data);
  AbstractLayout<Vertex, Edge> layout = getLayout(graph, layoutName);
  layout.setSize(new Dimension(width, height));

  BasicVisualizationServer<Vertex, Edge> viz = new BasicVisualizationServer<>(layout);
  viz.setPreferredSize(new Dimension(width, height));
  viz.getRenderContext().setEdgeLabelTransformer(edgeLabelTransformer);
  viz.getRenderContext().setVertexLabelTransformer(vertexLabelTransformer);
  viz.getRenderContext().setVertexFillPaintTransformer(vertexColorTransformer);

  BufferedImage bi = renderImage(viz);
  String imageType = null;
  if (mediaType.equals(CustomMediaTypes.IMAGE_JPEG_TYPE)) {
    imageType = "jpg";
  } else if (mediaType.equals(CustomMediaTypes.IMAGE_PNG_TYPE)) {
    imageType = "png";
  }
  ImageIO.write(bi, imageType, out);
}
 
示例7
@Override
public void writeTo(Graph data, Class<?> type, Type genericType, Annotation[] annotations,
    MediaType mediaType, MultivaluedMap<String, Object> headers, OutputStream out) throws IOException {
  try (Writer writer = new OutputStreamWriter(out);
      CSVPrinter printer = getCsvPrinter(writer)) {
    List<String> header = newArrayList("id", "label", "categories");
    printer.printRecord(header);
    List<String> vals = new ArrayList<>();
    for (Vertex vertex: data.getVertices()) {
      vals.clear();
      vals.add(getCurieOrIri(vertex));
      String label = getFirst(TinkerGraphUtil.getProperties(vertex, NodeProperties.LABEL, String.class), null);
      vals.add(label);
      vals.add(TinkerGraphUtil.getProperties(vertex, Concept.CATEGORY, String.class).toString());
      printer.printRecord(vals);
    }
  }
}
 
示例8
public FramedVertexList(final FramedGraph<? extends Graph> framedGraph, final Vertex sourceVertex, final Iterable<Vertex> list,
		final Class<T> kind) {
	super(framedGraph, list, ((DFramedTransactionalGraph) framedGraph).getReplacementType(kind));
	sourceVertex_ = sourceVertex;
	if (list instanceof List) {
		list_ = (List<Vertex>) list;
	} else {
		list_ = new ArrayList<Vertex>();
		Iterator<Vertex> itty = list.iterator();
		while (itty.hasNext()) {
			Vertex v = null;
			try {
				v = itty.next();
			} catch (Exception e) {
				//do nothing
			}
			if (v != null) {
				list_.add(v);
			}
		}
	}
}
 
示例9
@Override
public Graph configureGraphInstance(GraphConfigurationContext context) throws GraphConfigurationException {

  Configuration conf = context.getProperties();
  try {
    conf = ((HierarchicalConfiguration) conf).configurationAt(Tokens.REXSTER_GRAPH_PROPERTIES);
  } catch (IllegalArgumentException iae) {
    throw new GraphConfigurationException("Check graph configuration. Missing or empty configuration element: " + Tokens.REXSTER_GRAPH_PROPERTIES);
  }

  AccumuloGraphConfiguration cfg = new AccumuloGraphConfiguration(conf);
  if (cfg.getInstanceType().equals(InstanceType.Mock)) {
    cfg.setPassword("".getBytes());
    cfg.setUser("root");
  }
  cfg.setGraphName(context.getProperties().getString(Tokens.REXSTER_GRAPH_NAME));
  return GraphFactory.open(cfg.getConfiguration());
}
 
示例10
@Test
public void testPreloadSomeProperties() {
  AccumuloGraphConfiguration cfg =
      AccumuloGraphTestUtils.generateGraphConfig("preloadSomeProperties");
  cfg.setPropertyCacheTimeout(null, TIMEOUT);
  cfg.setPreloadedProperties(new String[]{CACHED});

  Graph graph = open(cfg);

  AccumuloVertex v = (AccumuloVertex) graph.addVertex("V");
  v.setProperty(NON_CACHED, true);
  v.setProperty(CACHED, true);

  v = (AccumuloVertex) graph.getVertex("V");
  assertEquals(null, v.getPropertyInMemory(NON_CACHED));
  assertEquals(true, v.getPropertyInMemory(CACHED));

  graph.shutdown();
}
 
示例11
/**
 * Get a single element by key, value.
 * 
 * @param graph The graph to get the element from
 * @param key The key of the element
 * @param value The value of the element
 * @param clazz The class element type, can be Vertex | Edge.
 * @return Found vertex that matches the specified criteria or null if not
 *         found.
 * @throws IllegalStateException if multiple vertices found that matches the
 *         specified criteria
 */
@SuppressWarnings("unchecked")
public static <E extends Element> E getSingleElement(Graph graph, String key, Object value, Class<E> clazz) {
    Iterable<?> it =
            Vertex.class.isAssignableFrom(clazz) ? graph.query().has(key, value).vertices() : graph.query().has(key, value).edges();
    Iterator<?> iter = it.iterator();

    E e = null;

    if (iter.hasNext()) {
        e = (E) iter.next();
    }

    return e;
}
 
示例12
public static Vertex addNode(Graph graph, Map<String, String> properties)
{
	Vertex newVertex = graph.addVertex(0);

	for (Entry<String, String> entrySet : properties.entrySet())
	{
		newVertex.setProperty(entrySet.getKey(), entrySet.getValue());
	}
	return newVertex;
}
 
示例13
private void linkToPreviousNode(String baseId, int num)
{
	String previousId = createCompleteId(baseId, num - 1);
	String thisId = createCompleteId(baseId, num);

	Graph graph = importer.getGraph();

	Vertex fromNode = graph.getVertex(previousId);
	Vertex toNode = graph.getVertex(thisId);

	graph.addEdge(0, fromNode, toNode, "foo");
}
 
示例14
private void copyFunctionEdges(Graph graph, Vertex functionRoot)
{
	GremlinPipeline<Vertex, Edge> pipe = new GremlinPipeline<>();
	pipe.start(functionRoot).as("loop")
			.out(EdgeTypes.IS_FUNCTION_OF, EdgeTypes.IS_BB_OF, EdgeTypes.READ, EdgeTypes.WRITE)
			.loop("loop", v -> true,
					v -> Arrays.asList(nodes)
							.contains(v.getObject().getProperty(BjoernNodeProperties.TYPE).toString()))
			.outE(edges);

	for (Edge e : pipe)
	{
		copyEdge(graph, e);
	}
}
 
示例15
/**
 * Add a vertex to the graph with specified id and provided properties.
 *
 * @param graph      the graph to create a vertex in
 * @param id         the id of the vertex to create
 * @param properties the properties of the vertex to add (must be String,Object,String,Object,...)
 * @return the vertex created in the graph with the provided properties set
 */
public static Vertex addVertex(final Graph graph, final Object id, final Object... properties) {
    if ((properties.length % 2) != 0)
        throw new RuntimeException("There must be an equal number of keys and values");
    final Vertex vertex = graph.addVertex(id);
    for (int i = 0; i < properties.length; i = i + 2) {
        vertex.setProperty((String) properties[i], properties[i + 1]);
    }
    return vertex;
}
 
示例16
public E processNextStart() {
    while (true) {
        if (this.count >= this.highRange) {
            throw FastNoSuchElementException.instance();
        } else if (this.currentIterator.hasNext()) {
            this.count++;
            final E e = currentIterator.next();
            if (this.count > this.lowRange)
                return e;
        } else {
            final Graph graph = this.starts.next();
            GraphQuery query = graph.query();
            if (null != this.hasContainers) {
                for (final HasContainer hasContainer : this.hasContainers) {
                    query = query.has(hasContainer.key, hasContainer.predicate, hasContainer.value);
                }
            }
            if (null != this.intervalContainers) {
                for (final IntervalContainer intervalContainer : this.intervalContainers) {
                    query = query.interval(intervalContainer.key, intervalContainer.startValue, intervalContainer.endValue);
                }
            }
            if (this.highRange != Integer.MAX_VALUE) {
                query = query.limit(this.highRange - this.count);
            }

            this.currentIterator = this.elementClass.equals(Vertex.class) ?
                    (Iterator<E>) query.vertices().iterator() :
                    (Iterator<E>) query.edges().iterator();
        }
    }
}
 
示例17
/**
 * Initializes Sesame repository for Neo4j based on Blueprints
 * implementation.
 *
 * @param database Neo4j database service
 * @throws RepositoryException if there was a problem initializing the
 * Sesame repository
 */
private RepositoryRegistry(GraphDatabaseService database)
		throws RepositoryException {
	initRio();
	Graph graph = new Neo4j2Graph(database);
	String patterns = SPARQLExtensionProps.getProperty("query.patterns");
	Sail sail = new GraphSail((KeyIndexableGraph) graph, patterns);
	this.rep = new SailRepository(sail);
	rep.initialize();
}
 
示例18
void addCuries(Graph graph) {
  for (Vertex vertex: graph.getVertices()) {
    String iri = (String)vertex.getProperty(CommonProperties.IRI);
    Optional<String> curie = curieUtil.getCurie(iri);
    if (curie.isPresent()) {
      vertex.setProperty(CommonProperties.CURIE, curie.get());
    }
  }
}
 
示例19
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
  Object result = invocation.proceed();
  if (result instanceof Graph) {
    addCuries((Graph)result);
  }
  return result;
}
 
示例20
public DTypeRegistry getTypeRegistry() {
	Graph graph = this.getBaseGraph();
	if (graph instanceof DGraph) {
		DConfiguration config = (DConfiguration) ((DGraph) graph).getConfiguration();
		return config.getTypeRegistry();
	}
	return null;
}
 
示例21
public void addGraph(Graph addition) {
  for (Vertex vertex : addition.getVertices()) {
    addElement(vertex);
  }
  for (Edge edge : addition.getEdges()) {
    addElement(edge);
  }
}
 
示例22
protected DFramedTransactionalGraph getGraph() {
	DGraph graph = getConfiguration().getGraph();
	Graph extGraph = graph.getExtendedGraph();
	if (extGraph instanceof DFramedTransactionalGraph) {
		return (DFramedTransactionalGraph) extGraph;
	} else {
		throw new IllegalStateException("Graph is a " + graph.getClass().getName());
	}
}
 
示例23
@Test
public void graphsAreMerged() {
  TinkerGraph graph1 = new TinkerGraph();
  Vertex g1v1 = graph1.addVertex(0);
  Vertex g1v2 = graph1.addVertex(1);
  Edge g1e1 = graph1.addEdge(0, g1v1, g1v2, "test");
  TinkerGraph graph2 = new TinkerGraph();
  Vertex g2v1 = graph2.addVertex(1);
  Vertex g2v2 = graph2.addVertex(2);
  Edge g2e1 = graph1.addEdge(1, g2v1, g2v2, "test2");
  TinkerGraphUtil tgu = new TinkerGraphUtil(graph1, curieUtil);
  Graph graph = tgu.combineGraphs(graph2);
  assertThat(graph.getVertices(), containsInAnyOrder(g1v1, g1v2, g2v2));
  assertThat(graph.getEdges(), containsInAnyOrder(g1e1, g2e1));
}
 
示例24
@Test
public void multipleAncestors_areReturned() {
  Graph graph = graphApi.getNeighbors(newHashSet(i), 10,
      newHashSet(new DirectedRelationshipType(OwlRelationships.RDFS_SUBCLASS_OF, Direction.OUTGOING)), absent);
  assertThat(graph.getVertices(), IsIterableWithSize.<Vertex>iterableWithSize(4));
  assertThat(graph.getEdges(), IsIterableWithSize.<Edge>iterableWithSize(4));
}
 
示例25
@Test
public void getReachableNodes_areReturned() {
  Graph graph = graphApi.getReachableNodes(b,
      Lists.newArrayList(OwlRelationships.RDFS_SUBCLASS_OF.name()), Sets.newHashSet());
  assertThat(size(graph.getVertices()), is(1));
  assertThat(size(graph.getEdges()), is(0));
  graph = graphApi.getReachableNodes(c,
      Lists.newArrayList(OwlRelationships.OWL_EQUIVALENT_CLASS.name(),
          OwlRelationships.RDFS_SUBCLASS_OF.name()),
      Sets.newHashSet());
  assertThat(size(graph.getVertices()), is(1));
  assertThat(size(graph.getEdges()), is(0));
}
 
示例26
@GET
@Path("/neighbors/{id}")
@ApiOperation(value = "Get neighbors", response = Graph.class)
@Timed
@CacheControl(maxAge = 2, maxAgeUnit = TimeUnit.HOURS)
@Produces({MediaType.APPLICATION_JSON, CustomMediaTypes.APPLICATION_GRAPHSON,
    MediaType.APPLICATION_XML, CustomMediaTypes.APPLICATION_GRAPHML,
    CustomMediaTypes.APPLICATION_XGMML, CustomMediaTypes.TEXT_GML, CustomMediaTypes.TEXT_CSV,
    CustomMediaTypes.TEXT_TSV, CustomMediaTypes.IMAGE_JPEG, CustomMediaTypes.IMAGE_PNG})
public Object getNeighbors(
    @ApiParam(value = DocumentationStrings.GRAPH_ID_DOC,
        required = true) @PathParam("id") String id,
    @ApiParam(value = "How far to traverse neighbors",
        required = false) @QueryParam("depth") @DefaultValue("1") IntParam depth,
    @ApiParam(value = "Traverse blank nodes",
        required = false) @QueryParam("blankNodes") @DefaultValue("false") BooleanParam traverseBlankNodes,
    @ApiParam(value = "Which relationship to traverse",
        required = false) @QueryParam("relationshipType") Set<String> relationshipTypes,
    @ApiParam(value = DocumentationStrings.DIRECTION_DOC, required = false,
        allowableValues = DocumentationStrings.DIRECTION_ALLOWED) @QueryParam("direction") @DefaultValue("BOTH") String direction,
    @ApiParam(value = "Should subproperties and equivalent properties be included",
        required = false) @QueryParam("entail") @DefaultValue("false") BooleanParam entail,
    @ApiParam(value = DocumentationStrings.PROJECTION_DOC,
        required = false) @QueryParam("project") @DefaultValue("*") Set<String> projection,
    @ApiParam(value = DocumentationStrings.JSONP_DOC,
        required = false) @QueryParam("callback") String callback) {
  return getNeighborsFromMultipleRoots(newHashSet(id), depth, traverseBlankNodes,
      relationshipTypes, direction, entail, projection, callback);
}
 
示例27
@Override
public Graph generateGraph(String graphDirectoryName) {
  Configuration cfg = new AccumuloGraphConfiguration()
    .setInstanceType(InstanceType.Distributed)
    .setZooKeeperHosts(ZOOKEEPERS)
    .setInstanceName(INSTANCE)
    .setUser(USER).setPassword(PASSWORD)
    .setGraphName(graphDirectoryName)
    .setCreate(true);
  testGraphName.set(graphDirectoryName);
  return GraphFactory.open(cfg);
}
 
示例28
@Override
public void writeTo(Graph data, Class<?> type, Type genericType, Annotation[] annotations,
    MediaType mediaType, MultivaluedMap<String, Object> headers, OutputStream out) throws IOException {
  BbopGraph bbopGraph = graphUtil.convertGraph(data);
  MAPPER.writeValue(out, bbopGraph);
  out.flush();
}
 
示例29
/**
 * Copy the vertex/edges of one graph over to another graph.
 * The id of the elements in the from graph are attempted to be used in the to graph.
 * This method only works for graphs where the user can control the element ids.
 *
 * @param from the graph to copy from
 * @param to   the graph to copy to
 */
public static void copyGraph(final Graph from, final Graph to) {
    for (final Vertex fromVertex : from.getVertices()) {
        final Vertex toVertex = to.addVertex(fromVertex.getId());
        ElementHelper.copyProperties(fromVertex, toVertex);
    }
    for (final Edge fromEdge : from.getEdges()) {
        final Vertex outVertex = to.getVertex(fromEdge.getVertex(Direction.OUT).getId());
        final Vertex inVertex = to.getVertex(fromEdge.getVertex(Direction.IN).getId());
        final Edge toEdge = to.addEdge(fromEdge.getId(), outVertex, inVertex, fromEdge.getLabel());
        ElementHelper.copyProperties(fromEdge, toEdge);
    }
}
 
示例30
@Test
public void write_doesntOutputNull() throws IOException {
  ByteArrayOutputStream os = new ByteArrayOutputStream();
  writer.writeTo(graph, Graph.class, null, null, null, null, os);
  String output = new String(os.toByteArray(), Charsets.UTF_8);
  assertThat(output, is(notNullValue()));
}