Java Code Examples for org.openrdf.model.Graph#add()

The following examples show how to use org.openrdf.model.Graph#add() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractTestNanoSparqlClient.java    From database with GNU General Public License v2.0 6 votes vote down vote up
/**
* Sets up a simple data set on the server.
* 
* @throws Exception
*/
protected void setupDataOnServer() throws Exception {
    
    final URI mike = new URIImpl(BD.NAMESPACE + "Mike");
    final URI bryan = new URIImpl(BD.NAMESPACE + "Bryan");
    final URI person = new URIImpl(BD.NAMESPACE + "Person");
    final URI likes = new URIImpl(BD.NAMESPACE + "likes");
    final URI rdf = new URIImpl(BD.NAMESPACE + "RDF");
    final URI rdfs = new URIImpl(BD.NAMESPACE + "RDFS");
    final Literal label1 = new LiteralImpl("Mike");
    final Literal label2 = new LiteralImpl("Bryan");

  {
     final Graph g = new LinkedHashModel();
     g.add(mike, RDF.TYPE, person);
     g.add(mike, likes, rdf);
     g.add(mike, RDFS.LABEL, label1);
     g.add(bryan, RDF.TYPE, person);
     g.add(bryan, likes, rdfs);
     g.add(bryan, RDFS.LABEL, label2);

     m_repo.add(new AddOp(g));
  }

}
 
Example 2
Source File: EntityStateSerializer.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
public void serialize( final EntityState entityState,
                       final boolean includeNonQueryable,
                       final Graph graph
)
{
    ValueFactory values = graph.getValueFactory();
    EntityReference reference = entityState.entityReference();
    URI entityUri = createEntityURI( values, reference );

    graph.add( entityUri,
               Rdfs.TYPE,
               values.createURI(
                   Classes.toURI( entityState.entityDescriptor().types().findFirst().orElse( null ) ) ) );

    serializeProperties( entityState,
                         graph,
                         entityUri,
                         entityState.entityDescriptor(),
                         includeNonQueryable );

    serializeAssociations( entityState,
                           graph,
                           entityUri,
                           entityState.entityDescriptor().state().associations(),
                           includeNonQueryable );

    serializeManyAssociations( entityState,
                               graph,
                               entityUri,
                               entityState.entityDescriptor().state().manyAssociations(),
                               includeNonQueryable );
}
 
Example 3
Source File: AbstractTestNanoSparqlClient.java    From database with GNU General Public License v2.0 5 votes vote down vote up
protected void doConstructTest(final String method, final RDFFormat format)
            throws Exception {
        
        setupDataOnServer();
        final URI mike = new URIImpl(BD.NAMESPACE + "Mike");
        final URI bryan = new URIImpl(BD.NAMESPACE + "Bryan");
        final URI person = new URIImpl(BD.NAMESPACE + "Person");

        // The expected results.
        final Graph expected = new LinkedHashModel();
        {
//            expected.add(new StatementImpl(mike, likes, rdf));
            expected.add(new StatementImpl(mike, RDF.TYPE, person));
            expected.add(new StatementImpl(bryan, RDF.TYPE, person));
//            expected.add(new StatementImpl(mike, RDFS.LABEL, label1));
        }
        
        // Run the query and verify the results.
        {

            final String queryStr =
                "prefix bd: <"+BD.NAMESPACE+"> " +//
                "prefix rdf: <"+RDF.NAMESPACE+"> " +//
                "prefix rdfs: <"+RDFS.NAMESPACE+"> " +//
                "CONSTRUCT { ?x rdf:type bd:Person }" +//
                "WHERE { " +//
                "  ?x rdf:type bd:Person . " +//
//                "  ?x bd:likes bd:RDF " +//
                "}";

            final IPreparedGraphQuery query = m_repo.prepareGraphQuery(queryStr);

//            final Graph actual = asGraph(query.evaluate());

            assertSameGraph(expected, query);
            
        }
    
    }
 
Example 4
Source File: AbstractTestNanoSparqlClient.java    From database with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Sets up a simple data set on the server.
* @throws Exception 
 */
protected void setupQuadsDataOnServer() throws Exception {
    
    final URI mike = new URIImpl(BD.NAMESPACE + "Mike");
    final URI bryan = new URIImpl(BD.NAMESPACE + "Bryan");
    final URI person = new URIImpl(BD.NAMESPACE + "Person");
    final URI likes = new URIImpl(BD.NAMESPACE + "likes");
    final URI rdf = new URIImpl(BD.NAMESPACE + "RDF");
    final URI rdfs = new URIImpl(BD.NAMESPACE + "RDFS");
    final URI c1 = new URIImpl(BD.NAMESPACE + "c1");
    final URI c2 = new URIImpl(BD.NAMESPACE + "c2");
    final URI c3 = new URIImpl(BD.NAMESPACE + "c3");
    final Literal label1 = new LiteralImpl("Mike");
    final Literal label2 = new LiteralImpl("Bryan");

  {
     final Graph g = new LinkedHashModel();
     g.add(mike, RDF.TYPE, person, c1, c2, c3);
     g.add(mike, likes, rdf, c1, c2, c3);
     g.add(mike, RDFS.LABEL, label1, c1, c2, c3);
     g.add(bryan, RDF.TYPE, person, c1, c2, c3);
     g.add(bryan, likes, rdfs, c1, c2, c3);
     g.add(bryan, RDFS.LABEL, label2, c1, c2, c3);
     m_repo.add(new AddOp(g));
  }

}
 
Example 5
Source File: BigdataSailConfig.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Resource export(Graph graph)
{
	Resource implNode = super.export(graph);

	if (propertiesFile != null) {
		graph.add(implNode, BigdataConfigSchema.PROPERTIES, 
                   graph.getValueFactory().createLiteral(propertiesFile));
	}

	return implNode;
}
 
Example 6
Source File: TestBigdataSailRemoteRepository.java    From database with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Test of insert and retrieval of a large literal.
 */
public void test_INSERT_veryLargeLiteral() throws Exception {

    final Graph g = new LinkedHashModel();
    
    final URI s = new URIImpl("http://www.bigdata.com/");
    final URI p = RDFS.LABEL;
    final Literal o = getVeryLargeLiteral();
    final Statement stmt = new StatementImpl(s, p, o);
    g.add(stmt);
    
    // Load the resource into the KB.
    assertEquals(
            1L,
            doInsertByBody("POST", RDFFormat.RDFXML, g, null/* defaultContext */));

    // Read back the data into a graph.
    final Graph g2;
    {
        final String queryStr = "DESCRIBE <" + s.stringValue() + ">";
        final GraphQuery query = cxn.prepareGraphQuery(QueryLanguage.SPARQL, queryStr);
        g2 = asGraph(query.evaluate());
        
    }
    
    assertEquals(1, g2.size());
    
    assertTrue(g2.match(s, p, o).hasNext());
    
}
 
Example 7
Source File: BigdataRepositoryConfig.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Resource export(Graph graph)
{
	Resource implNode = super.export(graph);

	if (propertiesFile != null) {
		graph.add(implNode, BigdataConfigSchema.PROPERTIES, 
                   graph.getValueFactory().createLiteral(propertiesFile));
	}

	return implNode;
}
 
Example 8
Source File: EntityStateSerializer.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
private void serializeProperty( PropertyDescriptor persistentProperty, Object property,
                                Resource subject, Graph graph,
                                boolean includeNonQueryable )
{
    if( !( includeNonQueryable || persistentProperty.queryable() ) )
    {
        return; // Skip non-queryable
    }

    ValueType valueType = persistentProperty.valueType();

    final ValueFactory valueFactory = graph.getValueFactory();

    String propertyURI = persistentProperty.qualifiedName().toURI();
    URI predicate = valueFactory.createURI( propertyURI );
    String baseURI = propertyURI.substring( 0, propertyURI.indexOf( '#' ) ) + "/";

    if( valueType instanceof ValueCompositeType )
    {
        serializeValueComposite( subject, predicate, (ValueComposite) property, valueType,
                                 graph, baseURI, includeNonQueryable );
    }
    else
    {
        String stringProperty = serializer.serialize( Serializer.Options.NO_TYPE_INFO, property );
        final Literal object = valueFactory.createLiteral( stringProperty );
        graph.add( subject, predicate, object );
    }
}
 
Example 9
Source File: ObjectRepositoryConfig.java    From anno4j with Apache License 2.0 5 votes vote down vote up
private void exportAssocation(Resource subj, Map<Class<?>, List<URI>> assocation,
		URI relation, Graph model) {
	ValueFactory vf = ValueFactoryImpl.getInstance();
	for (Map.Entry<Class<?>, List<URI>> e : assocation.entrySet()) {
		URI name = vf.createURI(JAVA_NS, e.getKey().getName());
		model.add(subj, relation, name);
		if (e.getValue() != null) {
			for (URI value : e.getValue()) {
				model.add(name, KNOWN_AS, value);
			}
		}
	}
}
 
Example 10
Source File: BigdataSailRemoteRepositoryConnection.java    From database with GNU General Public License v2.0 4 votes vote down vote up
@Override
   public <E extends Exception> void add(
           final Iteration<? extends Statement, E> stmts, final Resource... c)
           throws RepositoryException, E {
	
	final Graph g = new LinkedHashModel();

	while (stmts.hasNext()) {
	
	   g.add(stmts.next());
	   
	}
	
	add(g, c);
	
}
 
Example 11
Source File: Test_REST_DESCRIBE.java    From database with GNU General Public License v2.0 4 votes vote down vote up
protected void doStressDescribeTest(final String method,
      final RDFFormat format, final int tasks, final int threads,
      final int statements) throws Exception {

   final URI person = new URIImpl(BD.NAMESPACE + "Person");
   final URI likes = new URIImpl(BD.NAMESPACE + "likes");
   final URI rdf = new URIImpl(BD.NAMESPACE + "RDF");
   final URI rdfs = new URIImpl(BD.NAMESPACE + "RDFS");

   {
      // create a large number of mikes and bryans
      final Graph g = new GraphImpl();
      for (int n = 0; n < statements; n++) {
         final URI miken = new URIImpl(BD.NAMESPACE + "Mike#" + n);
         final URI bryann = new URIImpl(BD.NAMESPACE + "Bryan#" + n);
         final Literal nameMiken = new LiteralImpl("Mike#" + n);
         final Literal nameBryann = new LiteralImpl("Bryan#" + n);
         g.add(miken, RDF.TYPE, person);
         g.add(miken, likes, rdf);
         g.add(miken, RDFS.LABEL, nameMiken);
         g.add(bryann, RDF.TYPE, person);
         g.add(bryann, likes, rdfs);
         g.add(bryann, RDFS.LABEL, nameBryann);
      }

      m_repo.add(new AddOp(g));

   }

   // Run the DESCRIBE query and verify the results (non-empty).
   {

      final String queryStr = "prefix bd: <" + BD.NAMESPACE + "> " + //
            "prefix rdf: <" + RDF.NAMESPACE + "> " + //
            "prefix rdfs: <" + RDFS.NAMESPACE + "> " + //
            "DESCRIBE ?x " + //
            "WHERE { " + //
            "  ?x rdf:type bd:Person . " + //
            "  ?x bd:likes bd:RDF " + //
            "}";

      final AtomicInteger errorCount = new AtomicInteger();
      final Callable<Void> task = new Callable<Void>() {

         @Override
         public Void call() throws Exception {
            try {

               final Graph actual = asGraph(m_repo
                     .prepareGraphQuery(queryStr));

               assertTrue(!actual.isEmpty());

               return null;
            } catch (Exception e) {
               log.warn("Call failure", e);

               errorCount.incrementAndGet();

               throw e;
            }
         }

      };

      final int threadCount = Thread.activeCount();

      final ExecutorService exec = Executors.newFixedThreadPool(threads);
      for (int r = 0; r < tasks; r++) {
         exec.submit(task);
      }
      exec.shutdown();
      exec.awaitTermination(2000, TimeUnit.SECONDS);
      // force shutdown
      exec.shutdownNow();

      int loops = 20;
      while (Thread.activeCount() > threadCount && --loops > 0) {
         Thread.sleep(500);
         if (log.isTraceEnabled())
            log.trace("Extra threads: "
                  + (Thread.activeCount() - threadCount));
      }

      if (log.isInfoEnabled())
         log.info("Return with extra threads: "
               + (Thread.activeCount() - threadCount));

      assertTrue(errorCount.get() == 0);
   }

}
 
Example 12
Source File: DemoSesameServer.java    From database with GNU General Public License v2.0 4 votes vote down vote up
public static void _main(String[] args) throws Exception {

        String sesameURL, repoID;
        
        if (args != null && args.length == 2) {
            sesameURL = args[0];
            repoID = args[1];
        } else {
            sesameURL = DemoSesameServer.sesameURL;
            repoID = DemoSesameServer.repoID;
        }
        
        Repository repo = new HTTPRepository(sesameURL, repoID);
        repo.initialize();
        
        RepositoryConnection cxn = repo.getConnection();
        cxn.setAutoCommit(false);
        
        try { // load some statements built up programmatically
            
            URI mike = new URIImpl(BD.NAMESPACE + "Mike");
            URI bryan = new URIImpl(BD.NAMESPACE + "Bryan");
            URI loves = new URIImpl(BD.NAMESPACE + "loves");
            URI rdf = new URIImpl(BD.NAMESPACE + "RDF");
            Graph graph = new GraphImpl();
            graph.add(mike, loves, rdf);
            graph.add(bryan, loves, rdf);
            
            cxn.add(graph);
            cxn.commit();
            
        } finally {
            
            cxn.close();
            
        }
        
        { // show the entire contents of the repository

            SparqlBuilder sparql = new SparqlBuilder();
            sparql.addTriplePattern("?s", "?p", "?o");
            
            GraphQuery query = cxn.prepareGraphQuery(
                    QueryLanguage.SPARQL, sparql.toString());
            GraphQueryResult result = query.evaluate();
            while (result.hasNext()) {
                Statement stmt = result.next();
                System.err.println(stmt);
            }
            
        }
        
        
    }
 
Example 13
Source File: DescribeCacheUpdater.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Associate the statement with the resource. It is part of the
 * description of that resource.
 * 
 * @param describedResource
 *            A resource that is being described.
 * @param stmt
 *            A statement having that resource as either the subject or
 *            object.
 */
private void record(final BigdataValue describedResource,
        final BigdataStatement stmt) {

    Graph g = graphs.get(describedResource);
    
    if(g == null) {
        
        graphs.put(describedResource, g = new GraphImpl());

    }

    g.add(stmt);

    if (log.isDebugEnabled())
        log.debug("DESCRIBE: describedResource=" + describedResource
                + ", statement=" + stmt);

}
 
Example 14
Source File: AbstractTestNanoSparqlClient.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
 * @deprecated by {@link #asGraph(IPreparedGraphQuery)} which can ensure that
 *             the {@link GraphQueryResult} is closed.
 */
static protected Graph asGraph(final GraphQueryResult result) throws Exception {

   try {
      final Graph g = new LinkedHashModel();

      while (result.hasNext()) {

         g.add(result.next());

      }

      return g;
   } finally {
      result.close();
   }

}
 
Example 15
Source File: AbstractTestNanoSparqlClient.java    From database with GNU General Public License v2.0 4 votes vote down vote up
protected Graph genNTRIPLES2(final int ntriples)
		throws RDFHandlerException {

	final Graph g = new LinkedHashModel();

	final ValueFactory f = new ValueFactoryImpl();

	final URI s = f.createURI("http://www.bigdata.org/b");

	final URI rdfType = f
			.createURI("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");

	for (int i = 0; i < ntriples; i++) {

		final URI o = f.createURI("http://www.bigdata.org/c#" + i);

		g.add(s, rdfType, o);

	}
	
	return g;

}
 
Example 16
Source File: AbstractTestNanoSparqlClient.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Inserts some data into the KB and then issues a DESCRIBE query against
 * the REST API and verifies the expected results.
 * 
 * @param format
 *            The format is used to specify the Accept header.
 * 
 * @throws Exception
 */
protected void doDescribeTest(final String method, final RDFFormat format)
        throws Exception {
    
    final URI mike = new URIImpl(BD.NAMESPACE + "Mike");
    final URI bryan = new URIImpl(BD.NAMESPACE + "Bryan");
    final URI person = new URIImpl(BD.NAMESPACE + "Person");
    final URI likes = new URIImpl(BD.NAMESPACE + "likes");
    final URI rdf = new URIImpl(BD.NAMESPACE + "RDF");
    final URI rdfs = new URIImpl(BD.NAMESPACE + "RDFS");
    final Literal label1 = new LiteralImpl("Mike");
    final Literal label2 = new LiteralImpl("Bryan");

  {
     final Graph g = new LinkedHashModel();
     g.add(mike, RDF.TYPE, person);
     g.add(mike, likes, rdf);
     g.add(mike, RDFS.LABEL, label1);
     g.add(bryan, RDF.TYPE, person);
     g.add(bryan, likes, rdfs);
     g.add(bryan, RDFS.LABEL, label2);

     m_repo.add(new AddOp(g));
  }

    // The expected results.
    final Graph expected = new LinkedHashModel();
    {
        expected.add(new StatementImpl(mike, likes, rdf));
        expected.add(new StatementImpl(mike, RDF.TYPE, person));
        expected.add(new StatementImpl(mike, RDFS.LABEL, label1));
    }
    
    // Run the query and verify the results.
    {
        
    	final String queryStr =
            "prefix bd: <"+BD.NAMESPACE+"> " +//
            "prefix rdf: <"+RDF.NAMESPACE+"> " +//
            "prefix rdfs: <"+RDFS.NAMESPACE+"> " +//
            "DESCRIBE ?x " +//
            "WHERE { " +//
            "  ?x rdf:type bd:Person . " +//
            "  ?x bd:likes bd:RDF " +//
            "}";

    	assertSameGraph(expected, m_repo.prepareGraphQuery(queryStr));
        
    }

}
 
Example 17
Source File: EntityStateSerializer.java    From attic-polygene-java with Apache License 2.0 4 votes vote down vote up
private void serializeValueComposite( Resource subject, URI predicate,
                                      ValueComposite value,
                                      ValueType valueType,
                                      Graph graph,
                                      String baseUri,
                                      boolean includeNonQueryable
)
{
    final ValueFactory valueFactory = graph.getValueFactory();
    BNode collection = valueFactory.createBNode();
    graph.add( subject, predicate, collection );

    ( (ValueCompositeType) valueType ).properties().forEach(
        persistentProperty ->
        {
            Object propertyValue
                = PolygeneAPI.FUNCTION_COMPOSITE_INSTANCE_OF
                .apply( value )
                .state()
                .propertyFor( persistentProperty.accessor() )
                .get();

            if( propertyValue != null )
            {
                ValueType type = persistentProperty
                    .valueType();
                if( type instanceof ValueCompositeType )
                {
                    URI pred = valueFactory.createURI( baseUri,
                                                       persistentProperty
                                                           .qualifiedName()
                                                           .name() );
                    serializeValueComposite( collection, pred,
                                             (ValueComposite) propertyValue,
                                             type, graph,
                                             baseUri
                                             + persistentProperty
                                                 .qualifiedName()
                                                 .name() + "/",
                                             includeNonQueryable );
                }
                else
                {
                    serializeProperty( persistentProperty,
                                       propertyValue,
                                       collection, graph,
                                       includeNonQueryable );
                }
            }
        } );
}
 
Example 18
Source File: BigdataSailRemoteRepositoryConnection.java    From database with GNU General Public License v2.0 3 votes vote down vote up
/**
    * <strong>single statement updates not recommended for performance
    * reasons</strong>. Remember, batch is beautiful.
    * <p>
    * {@inheritDoc}
    */
	@Override
	public void add(final Statement stmt, final Resource... c)
			throws RepositoryException {

//		log.warn("single statement updates not recommended");
		
		final Graph g = new LinkedHashModel();

		g.add(stmt);
		
		add(g, c);

	}
 
Example 19
Source File: RemoteRepositoryBase.java    From database with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Utility method to turn a {@link GraphQueryResult} into a {@link Graph}.
 * 
 * @param result
 *            The {@link GraphQueryResult}.
 * 
 * @return The {@link Graph}.
 * 
 * @throws Exception
 */
static public Graph asGraph(final GraphQueryResult result) throws Exception {

    final Graph g = new LinkedHashModel();

    while (result.hasNext()) {

        g.add(result.next());

    }

    return g;

}
 
Example 20
Source File: BigdataSailRemoteRepositoryConnection.java    From database with GNU General Public License v2.0 3 votes vote down vote up
/**
    * <strong>single statement updates not recommended for performance
    * reasons</strong>. Remember, batch is beautiful.
    * <p>
    * {@inheritDoc}
    */
    @Override
	public void remove(final Statement stmt, final Resource... c)
			throws RepositoryException {
		
//		log.warn("single statement updates not recommended");
		
		final Graph g = new LinkedHashModel();
	
		g.add(stmt);
		
		remove(g, c);

	}