예제 #1
0
파일: graph.c 프로젝트: ged/redleaf
/*
 * call-seq:
 *   graph.dup   -> graph
 *
 * Duplicate the receiver and return the copy.
 *
 */
static VALUE
rleaf_redleaf_graph_dup( VALUE self ) {
	rleaf_GRAPH *ptr = rleaf_get_graph( self );
	VALUE dup = rleaf_redleaf_graph_s_allocate( CLASS_OF(self) );
	rleaf_GRAPH *dup_ptr = ALLOC( rleaf_GRAPH );
	librdf_stream *statements = librdf_model_as_stream( ptr->model );

	rleaf_log_with_context( self, "debug", "Duping %s 0x%x", rb_obj_classname(self), self );

	dup_ptr->store = ptr->store;
	dup_ptr->model = librdf_new_model_from_model( ptr->model );
	if ( ! dup_ptr->model ) {
		librdf_free_stream( statements );
		xfree( dup_ptr );
		rb_raise( rleaf_eRedleafError, "couldn't create new model from model <%p>", ptr->model );
	}

	if ( (librdf_model_add_statements(dup_ptr->model, statements)) != 0 ) {
		librdf_free_stream( statements );
		librdf_free_model( dup_ptr->model );
		xfree( dup_ptr );
		rb_raise( rleaf_eRedleafError, "couldn't add statements from the original model" );
	}

	DATA_PTR( dup ) = dup_ptr;
	OBJ_INFECT( dup, self );

	return dup;
}
예제 #2
0
/**
 * librdf_storage_context_remove_statements - Remove statements from a storage with the given context
 * @storage: &librdf_storage object
 * @context: &librdf_uri context
 * 
 * If @context is NULL, this is equivalent to librdf_storage_remove_statements
 *
 * Return value: Non 0 on failure
 **/
int
librdf_storage_context_remove_statements(librdf_storage* storage,
                                         librdf_node* context) 
{
  librdf_stream *stream;

  LIBRDF_ASSERT_OBJECT_POINTER_RETURN_VALUE(storage, librdf_storage, 1);

  if(storage->factory->context_remove_statements)
    return storage->factory->context_remove_statements(storage, context);
  
  if(!storage->factory->context_remove_statement)
    return 1;
  
  stream=librdf_storage_context_as_stream(storage, context);
  if(!stream)
    return 1;

  while(!librdf_stream_end(stream)) {
    librdf_statement *statement=librdf_stream_get_object(stream);
    if(!statement)
      break;
    librdf_storage_context_remove_statement(storage, context, statement);
    librdf_stream_next(stream);
  }
  librdf_free_stream(stream);  
  return 0;
}
예제 #3
0
파일: graph.c 프로젝트: ged/redleaf
/*
 * call-seq:
 *   graph.remove( statement )   -> array
 *
 * Removes one or more statements from the graph that match the specified +statement+
 * (either a Redleaf::Statement or a valid triple in an Array) and returns any that
 * were removed.
 *
 * Any +nil+ values in the statement will match any value.
 *
 *   # Set a new home page for the Redleaf project, preserving the old one
 *   # as the 'old_homepage'
 *   stmt = graph.remove([ :Redleaf, DOAP[:homepage], nil ])
 *   stmt.predicate = DOAP[:old_homepage]
 *   graph.append( stmt )
 *   graph.append([ :Redleaf, DOAP[:homepage],
 *                  URL.parse('http://deveiate.org/projects/Redleaf') ])
 */
static VALUE
rleaf_redleaf_graph_remove( VALUE self, VALUE statement ) {
	rleaf_GRAPH *ptr = rleaf_get_graph( self );
	librdf_statement *search_statement, *stmt;
	librdf_stream *stream;
	int count = 0;
	VALUE rval = rb_ary_new();

	rleaf_log_with_context( self, "debug", "removing statements matching %s",
		RSTRING_PTR(rb_inspect(statement)) );
	search_statement = rleaf_value_to_librdf_statement( statement );
 	stream = librdf_model_find_statements( ptr->model, search_statement );

	if ( !stream ) {
		librdf_free_statement( search_statement );
		rb_raise( rleaf_eRedleafError, "could not create a stream when removing %s from %s",
		 	RSTRING_PTR(rb_inspect(statement)),
			RSTRING_PTR(rb_inspect(self)) );
	}

	while ( ! librdf_stream_end(stream) ) {
		if ( (stmt = librdf_stream_get_object( stream )) == NULL ) break;

		count++;
		rb_ary_push( rval, rleaf_librdf_statement_to_value(stmt) );

		if ( librdf_model_remove_statement(ptr->model, stmt) != 0 ) {
			librdf_free_stream( stream );
			librdf_free_statement( search_statement );
			rb_raise( rleaf_eRedleafError, "failed to remove statement from model" );
		}

		librdf_stream_next( stream );
	}

	rleaf_log_with_context( self, "debug", "removed %d statements", count );

	librdf_free_stream( stream );
	librdf_free_statement( search_statement );

	return rval;
}
예제 #4
0
redhttp_response_t *handle_description_get(redhttp_request_t * request, void *user_data)
{
  const raptor_syntax_description* desc = NULL;
  redhttp_response_t *response = NULL;
  librdf_storage *sd_storage = NULL;
  librdf_model *sd_model = NULL;
  librdf_stream *sd_stream = NULL;

  desc = redstore_negotiate_format(request, librdf_serializer_get_description, "text/html", NULL);
  if (desc == NULL || strcmp("html", desc->names[0])==0) {
    response = handle_html_description(request, user_data);
  } else {
    const char *request_url = redhttp_request_get_url(request);

    sd_storage = librdf_new_storage(world, NULL, NULL, NULL);
    if (!sd_storage) {
      redstore_error("Failed to create temporary storage for service description.");
      goto CLEANUP;
    }

    sd_model = create_service_description(sd_storage, request_url);
    if (!sd_model) {
      redstore_error("Failed to create model for service description.");
      goto CLEANUP;
    }

    sd_stream = librdf_model_as_stream(sd_model);
    if (!sd_stream) {
      redstore_error("Failed to create stream for service description.");
      goto CLEANUP;
    }

    response = format_graph_stream(request, sd_stream);
    if (!response) {
      redstore_error("Failed to create temporary storage for service description.");
      goto CLEANUP;
    }
  }


CLEANUP:
  if (sd_stream)
    librdf_free_stream(sd_stream);
  if (sd_model)
    librdf_free_model(sd_model);
  if (sd_storage)
    librdf_free_storage(sd_storage);

  return response;
}
예제 #5
0
static void
rasqal_redland_finish_triples_match(struct rasqal_triples_match_s* rtm,
                                    void *user_data)
{
  rasqal_redland_triples_match_context* rtmc=(rasqal_redland_triples_match_context*)rtm->user_data;

  if(rtmc) {
    if(rtmc->stream) {
      librdf_free_stream(rtmc->stream);
      rtmc->stream=NULL;
    }
    if(rtmc->qstatement)
      librdf_free_statement(rtmc->qstatement);
    LIBRDF_FREE(rasqal_redland_triples_match_context, rtmc);
  }
}
예제 #6
0
파일: graph.c 프로젝트: ged/redleaf
/*
 * call-seq:
 *   graph.search( subject, predicate, object )   -> array
 *   graph[ subject, predicate, object ]          -> array
 *
 * Search for statements in the graph with the specified +subject+, +predicate+, and +object+ and
 * return them. If +subject+, +predicate+, or +object+ are nil, they will match any value.
 *
 *   # Match any statements about authors
 *   graph.load( 'http://deveiant.livejournal.com/data/foaf' )
 *
 *   #
 *   graph[ nil, FOAF[:knows], nil ]  # => [...]
 */
static VALUE
rleaf_redleaf_graph_search( VALUE self, VALUE subject, VALUE predicate, VALUE object ) {
	rleaf_GRAPH *ptr = rleaf_get_graph( self );
	librdf_node *subject_node, *predicate_node, *object_node;
	librdf_statement *search_statement, *stmt;
	librdf_stream *stream;
	int count = 0;
	VALUE rval = rb_ary_new();

	rleaf_log_with_context( self, "debug", "searching for statements matching {%s, %s, %s}",
		RSTRING_PTR(rb_inspect(subject)),
		RSTRING_PTR(rb_inspect(predicate)),
		RSTRING_PTR(rb_inspect(object)) );

	subject_node   = rleaf_value_to_subject_node( subject );
	predicate_node = rleaf_value_to_predicate_node( predicate );
	object_node    = rleaf_value_to_object_node( object );

	search_statement = librdf_new_statement_from_nodes( rleaf_rdf_world, subject_node, predicate_node, object_node );
	if ( !search_statement )
		rb_raise( rleaf_eRedleafError, "could not create a statement from nodes [%s, %s, %s]",
			RSTRING_PTR(rb_inspect(subject)),
			RSTRING_PTR(rb_inspect(predicate)),
			RSTRING_PTR(rb_inspect(object)) );

 	stream = librdf_model_find_statements( ptr->model, search_statement );
	if ( !stream ) {
		librdf_free_statement( search_statement );
		rb_raise( rleaf_eRedleafError, "could not create a stream when searching" );
	}

	while ( ! librdf_stream_end(stream) ) {
		stmt = librdf_stream_get_object( stream );
		if ( !stmt ) break;

		count++;
		rb_ary_push( rval, rleaf_librdf_statement_to_value(stmt) );
		librdf_stream_next( stream );
	}

	rleaf_log_with_context( self, "debug", "found %d statements", count );

	librdf_free_stream( stream );
	librdf_free_statement( search_statement );

	return rval;
}
예제 #7
0
static int
librdf_serializer_raptor_serialize_model(void *context,
                                         FILE *handle, librdf_uri* base_uri,
                                         librdf_model *model) 
{
  /* librdf_serializer_raptor_context* pcontext=(librdf_serializer_raptor_context*)context; */

  librdf_stream *stream=librdf_model_as_stream(model);
  if(!stream)
    return 1;
  while(!librdf_stream_end(stream)) {
    librdf_statement *statement=librdf_stream_get_object(stream);
    librdf_serializer_print_statement_as_ntriple(statement, handle);
    fputc('\n', handle);
    librdf_stream_next(stream);
  }
  librdf_free_stream(stream);
  return 0;
}
예제 #8
0
파일: graph.c 프로젝트: ged/redleaf
/*
 * call-seq:
 *   graph.statements   -> array
 *
 * Return an Array of all the statements in the graph.
 *
 */
static VALUE
rleaf_redleaf_graph_statements( VALUE self ) {
	rleaf_GRAPH *ptr = rleaf_get_graph( self );
	librdf_stream *stream = librdf_model_as_stream( ptr->model );
	VALUE statements = rb_ary_new();

	rleaf_log_with_context( self, "debug",
		"Creating statement objects for %d statements in Graph <0x%x>.",
		librdf_model_size(ptr->model), self );
	while ( ! librdf_stream_end(stream) ) {
		librdf_statement *stmt = librdf_stream_get_object( stream );
		VALUE stmt_obj = rleaf_librdf_statement_to_value( stmt );

		rb_ary_push( statements, stmt_obj );
		librdf_stream_next( stream );
	}
	librdf_free_stream( stream );

	return statements;
}
예제 #9
0
파일: RDF.c 프로젝트: Webo/DEFOREST
/**
 * @brief Executes the given query and returns the result in the given format.
 *
 *
 * @param query The query to execute.
 * @param format The format of the result.
 * 
 * @return The results.
 */
unsigned char* RDF_ExecQuery(unsigned char* query, unsigned char* format)
{   
    librdf_query* rdfquery;
    librdf_query_results* results;
           
    rdfquery = librdf_new_query(world, "sparql", NULL, query, NULL);
    results = librdf_model_query_execute(model, rdfquery);             
        
    librdf_serializer* serializer;
    librdf_stream* stream;

    serializer = librdf_new_serializer(world, format, NULL, NULL);
    
    if(!serializer) 
    {
      fprintf(stderr,
              "Failed to create triples serializer for format '%s'\n",
              format);
      return NULL;
    }

    stream = librdf_query_results_as_stream(results);
    unsigned char* result = librdf_serializer_serialize_stream_to_string(serializer,
               NULL, stream);    

    if(!result) 
    {
      fprintf(stderr, "Failed to turn query results to format '%s'\n",
              format);
      return NULL;
    }
    
    librdf_free_query(rdfquery);
    librdf_free_query_results(results);
    librdf_free_serializer(serializer);
    librdf_free_stream(stream);
    
    return result;
}
예제 #10
0
파일: graph.c 프로젝트: ged/redleaf
/*
 * call-seq:
 *   graph.each_statement {|statement| block }   -> graph
 *   graph.each {|statement| block }             -> graph
 *
 * Call +block+ once for each statement in the graph.
 *
 */
static VALUE
rleaf_redleaf_graph_each_statement( VALUE self ) {
	rleaf_GRAPH *ptr = rleaf_get_graph( self );
	librdf_stream *stream;
	librdf_statement *stmt;

	stream = librdf_model_as_stream( ptr->model );
	if ( !stream )
		rb_raise( rleaf_eRedleafError, "Failed to create stream for graph" );

	while ( ! librdf_stream_end(stream) ) {
		stmt = librdf_stream_get_object( stream );
		if ( !stmt ) break;

		rb_yield( rleaf_librdf_statement_to_value(stmt) );
		librdf_stream_next( stream );
	}

	librdf_free_stream( stream );

	return self;
}
예제 #11
0
static void
librdf_storage_stream_to_node_iterator_finished(void* iterator) 
{
  librdf_storage_stream_to_node_iterator_context* context=(librdf_storage_stream_to_node_iterator_context*)iterator;
  librdf_statement *partial_statement=context->partial_statement;

  /* make sure librdf_free_statement() doesn't free anything here */
  if(partial_statement) {
    librdf_statement_set_subject(partial_statement, NULL);
    librdf_statement_set_predicate(partial_statement, NULL);
    librdf_statement_set_object(partial_statement, NULL);

    librdf_free_statement(partial_statement);
  }

  if(context->stream)
    librdf_free_stream(context->stream);

  if(context->storage)
    librdf_storage_remove_reference(context->storage);
  
  LIBRDF_FREE(librdf_storage_stream_to_node_iterator_context, context);
}
예제 #12
0
파일: graph.c 프로젝트: ged/redleaf
/*
 * call-seq:
 *   graph.include?( statement )    -> true or false
 *   graph.contains?( statement )   -> true or false
 *
 * Return +true+ if the receiver contains the specified +statement+, which can be either a
 * Redleaf::Statement object or a valid triple in an Array.
 *
 */
static VALUE
rleaf_redleaf_graph_include_p( VALUE self, VALUE statement ) {
	rleaf_GRAPH *ptr = rleaf_get_graph( self );
	librdf_statement *stmt;
	librdf_stream *stream;
	VALUE rval = Qfalse;

	rleaf_log_with_context( self, "debug", "checking for statement matching %s",
		RSTRING_PTR(rb_inspect(statement)) );
	stmt = rleaf_value_to_librdf_statement( statement );

	/* According to the Redland docs, this is a better way to test this than
	   librdf_model_contains_statement if the model has contexts. Since we want
	   to support contexts, it's easier just to assume that they're always enabled.
	 */
	stream = librdf_model_find_statements( ptr->model, stmt );
	if ( stream != NULL && !librdf_stream_end(stream) ) rval = Qtrue;

	librdf_free_stream( stream );
	librdf_free_statement( stmt );

	return rval;
}
예제 #13
0
int
main(int argc, char *argv[])
{
  librdf_world* world;
  librdf_parser* parser;
  librdf_serializer* serializer;
  librdf_storage *storage;
  librdf_model* model;
  librdf_node *source, *arc, *target, *node;
  librdf_node *subject, *predicate, *object;
  librdf_node* context_node=NULL;
  librdf_stream* stream;
  librdf_iterator* iterator;
  librdf_uri *uri;
  librdf_uri *base_uri=NULL;
  librdf_query *query;
  librdf_query_results *results;
  librdf_hash *options;
  int count;
  int rc;
  int transactions=0;
  const char* storage_name;
  const char* storage_options;
  const char* context;
  const char* identifier;
  const char* results_format;
  librdf_statement* statement=NULL;
  char* query_cmd=NULL;
  char* s;


  /*
   * Initialize
   */
  storage_name="virtuoso";
  results_format="xml";
  context=DEFAULT_CONTEXT;
  identifier=DEFAULT_IDENTIFIER;


  /*
   * Get connection options
   */
  if(argc == 2 && argv[1][0] != '\0')
    storage_options=argv[1];
  else if((s=getenv ("VIRTUOSO_STORAGE_OPTIONS")) != NULL)
    storage_options=s;
  else
    storage_options=DEFAULT_STORAGE_OPTIONS;


  world=librdf_new_world();

  librdf_world_set_logger(world, world, log_handler);

  librdf_world_open(world);

  options=librdf_new_hash(world, NULL);
  librdf_hash_open(options, NULL, 0, 1, 1, NULL);

  librdf_hash_put_strings(options, "contexts", "yes");
  transactions=1;

  librdf_hash_from_string(options, storage_options);

  storage=librdf_new_storage_with_options(world, storage_name, identifier, options);

  if(!storage) {
    fprintf(stderr, ": Failed to open %s storage '%s'\n", storage_name, identifier);
    return(1);
  }

  model=librdf_new_model(world, storage, NULL);
  if(!model) {
    fprintf(stderr, ": Failed to create model\n");
    return(1);
  }

  if(transactions)
    librdf_model_transaction_start(model);

  /* Do this or gcc moans */
  stream=NULL;
  iterator=NULL;
  parser=NULL;
  serializer=NULL;
  source=NULL;
  arc=NULL;
  target=NULL;
  subject=NULL;
  predicate=NULL;
  object=NULL;
  uri=NULL;
  node=NULL;
  query=NULL;
  results=NULL;
  context_node=librdf_new_node_from_uri_string(world, (const unsigned char *)context);


  /**** Test 1 *******/
  startTest(1, " Remove all triples in <%s> context\n", context);
  {
    rc=librdf_model_context_remove_statements(model, context_node);

    if(rc)
      endTest(0, " failed to remove context triples from the graph\n");
    else
      endTest(1, " removed context triples from the graph\n");
  }


  /**** Test 2 *******/
  startTest(2, " Add triples to <%s> context\n", context);
  {
    rc=0;
    rc |= add_triple(world, context_node, model, "aa", "bb", "cc");
    rc |= add_triple(world, context_node, model, "aa", "bb1", "cc");
    rc |= add_triple(world, context_node, model, "aa", "a2", "_:cc");
    rc |= add_triple_typed(world, context_node, model, "aa", "a2", "cc");
    rc |= add_triple_typed(world, context_node, model, "mm", "nn", "Some long literal with language@en");
    rc |= add_triple_typed(world, context_node, model, "oo", "pp", "12345^^<http://www.w3.org/2001/XMLSchema#int>");
    if(rc)
      endTest(0, " failed add triple\n");
    else
      endTest(1, " add triple to context\n");
  }


  /**** Test 3 *******/
  startTest(3, " Print all triples in <%s> context\n", context);
  {
    raptor_iostream* iostr = raptor_new_iostream_to_file_handle(librdf_world_get_raptor(world), stdout);
    librdf_model_write(model, iostr);
    raptor_free_iostream(iostr);
    endTest(1, "\n");
  }


  /***** Test 4 *****/
  startTest(4, " Count of triples in <%s> context\n", context);
  {
    count=librdf_model_size(model);
    if(count >= 0)
      endTest(1, " graph has %d triples\n", count);
    else
      endTest(0, " graph has unknown number of triples\n");
  }


  /***** Test 5 *****/
  startTest(5, " Exec:  ARC  aa bb \n");
  {
    subject=librdf_new_node_from_uri_string(world, (const unsigned char*)"aa");
    predicate=librdf_new_node_from_uri_string(world, (const unsigned char*)"bb");
    node=librdf_model_get_target(model, subject, predicate);
    librdf_free_node(subject);
    librdf_free_node(predicate);
    if(!node) {
      endTest(0, " Failed to get arc\n");
    } else {
      print_node(stdout, node);
      librdf_free_node(node);
      endTest(1, "\n");
    }
  }


  /***** Test 6 *****/
  startTest(6, " Exec:  ARCS  aa cc \n");
  {
    subject=librdf_new_node_from_uri_string(world, (const unsigned char*)"aa");
    object=librdf_new_node_from_uri_string(world, (const unsigned char*)"cc");
    iterator=librdf_model_get_arcs(model, subject, object);
    librdf_free_node(subject);
    librdf_free_node(object);
    if(!iterator) {
      endTest(0, " Failed to get arcs\n");
    } else {
      print_nodes(stdout, iterator);
      endTest(1, "\n");
    }
  }


  /***** Test 7 *****/
  startTest(7, " Exec:  ARCS-IN  cc \n");
  {
    object=librdf_new_node_from_uri_string(world, (const unsigned char*)"cc");
    iterator=librdf_model_get_arcs_in(model, object);
    librdf_free_node(object);
    if(!iterator) {
      endTest(0, " Failed to get arcs in\n");
    } else {
      int ok=1;
      count=0;
      while(!librdf_iterator_end(iterator)) {
        context_node=(librdf_node*)librdf_iterator_get_context(iterator);
        node=(librdf_node*)librdf_iterator_get_object(iterator); /*returns SHARED pointer */
        if(!node) {
          ok=0;
          endTest(ok, " librdf_iterator_get_next returned NULL\n");
          break;
        }

        fputs("Matched arc: ", stdout);
        librdf_node_print(node, stdout);
        if(context_node) {
          fputs(" with context ", stdout);
          librdf_node_print(context_node, stdout);
        }
        fputc('\n', stdout);

        count++;
        librdf_iterator_next(iterator);
      }
      librdf_free_iterator(iterator);
      endTest(ok, " matching arcs: %d\n", count);
    }
  }


  /***** Test 8 *****/
  startTest(8, " Exec:  ARCS-OUT  aa \n");
  {
    subject=librdf_new_node_from_uri_string(world, (const unsigned char*)"aa");
    iterator=librdf_model_get_arcs_out(model, subject);
    librdf_free_node(subject);
    if(!iterator)
      endTest(0, " Failed to get arcs out\n");
    else {
      int ok=1;
      count=0;
      while(!librdf_iterator_end(iterator)) {
        context_node=(librdf_node*)librdf_iterator_get_context(iterator);
        node=(librdf_node*)librdf_iterator_get_object(iterator);
        if(!node) {
          ok=0;
          endTest(ok, " librdf_iterator_get_next returned NULL\n");
          break;
        }

        fputs("Matched arc: ", stdout);
        librdf_node_print(node, stdout);
        if(context_node) {
          fputs(" with context ", stdout);
          librdf_node_print(context_node, stdout);
        }
        fputc('\n', stdout);

        count++;
        librdf_iterator_next(iterator);
      }
      librdf_free_iterator(iterator);
      endTest(ok, " matching arcs: %d\n", count);
    }
  }


  /***** Test 9 *****/
  startTest(9, " Exec:  CONTAINS aa bb1 cc \n");
  {
    subject=librdf_new_node_from_uri_string(world, (const unsigned char*)"aa");
    predicate=librdf_new_node_from_uri_string(world, (const unsigned char*)"bb1");
    object=librdf_new_node_from_uri_string(world, (const unsigned char*)"cc");
    statement=librdf_new_statement(world);
    librdf_statement_set_subject(statement, subject);
    librdf_statement_set_predicate(statement, predicate);
    librdf_statement_set_object(statement, object);

    if(librdf_model_contains_statement(model, statement))
       endTest(1, " the graph contains the triple\n");
    else
       endTest(0, " the graph does not contain the triple\n");

    librdf_free_statement(statement);
  }


  /***** Test 10 *****/
  startTest(10, " Exec:  FIND aa - - \n");
  {
    subject=librdf_new_node_from_uri_string(world, (const unsigned char*)"aa");
    statement=librdf_new_statement(world);
    librdf_statement_set_subject(statement, subject);

    stream=librdf_model_find_statements_in_context(model, statement, context_node);

    if(!stream) {
        endTest(0, " FIND returned no results (NULL stream)\n");
    } else {
        librdf_node* ctxt_node=NULL;
        int ok=1;
        count=0;
        while(!librdf_stream_end(stream)) {
          librdf_statement *stmt=librdf_stream_get_object(stream);
          ctxt_node=(librdf_node*)librdf_stream_get_context(stream);
          if(!stmt) {
              ok=0;
              endTest(ok, " librdf_stream_next returned NULL\n");
              break;
          }

          fputs("Matched triple: ", stdout);
          librdf_statement_print(stmt, stdout);
          if(context) {
              fputs(" with context ", stdout);
              librdf_node_print(ctxt_node, stdout);
          }
          fputc('\n', stdout);

          count++;
          librdf_stream_next(stream);
        }
        librdf_free_stream(stream);
        endTest(ok, " matching triples: %d\n", count);
    }

    librdf_free_statement(statement);
  }


  /***** Test 11 *****/
  startTest(11, " Exec:  HAS-ARC-IN cc bb \n");
  {
    predicate=librdf_new_node_from_uri_string(world, (const unsigned char*)"bb");
    object=librdf_new_node_from_uri_string(world, (const unsigned char*)"cc");

    if(librdf_model_has_arc_in(model, object, predicate))
        endTest(1, " the graph contains the arc\n");
      else
        endTest(0, " the graph does not contain the arc\n");

    librdf_free_node(predicate);
    librdf_free_node(object);
  }


  /***** Test 12 *****/
  startTest(12, " Exec:  HAS-ARC-OUT aa bb \n");
  {
    subject=librdf_new_node_from_uri_string(world, (const unsigned char*)"aa");
    predicate=librdf_new_node_from_uri_string(world, (const unsigned char*)"bb");

    if(librdf_model_has_arc_out(model, subject, predicate))
        endTest(1, " the graph contains the arc\n");
      else
        endTest(0, " the graph does not contain the arc\n");

    librdf_free_node(predicate);
    librdf_free_node(subject);
  }


  /***** Test 13 *****/
  startTest(13, " Exec:  SOURCE  aa cc \n");
  {
    predicate=librdf_new_node_from_uri_string(world, (const unsigned char*)"bb");
    object=librdf_new_node_from_uri_string(world, (const unsigned char*)"cc");

    node=librdf_model_get_source(model, predicate, object);
    librdf_free_node(predicate);
    librdf_free_node(object);
    if(!node) {
      endTest(0, " Failed to get source\n");
    } else {
      print_node(stdout, node);
      librdf_free_node(node);
      endTest(1, "\n");
    }
  }


  /***** Test 14 *****/
  startTest(14, " Exec:  SOURCES  bb cc \n");
  {
    predicate=librdf_new_node_from_uri_string(world, (const unsigned char*)"bb");
    object=librdf_new_node_from_uri_string(world, (const unsigned char*)"cc");

    iterator=librdf_model_get_sources(model, predicate, object);
    librdf_free_node(predicate);
    librdf_free_node(object);
    if(!iterator) {
      endTest(0, " Failed to get sources\n");
    } else {
      print_nodes(stdout, iterator);
      endTest(1, "\n");
    }
  }


  /***** Test 15 *****/
  startTest(15, " Exec:  TARGET  aa bb \n");
  {
    subject=librdf_new_node_from_uri_string(world, (const unsigned char*)"aa");
    predicate=librdf_new_node_from_uri_string(world, (const unsigned char*)"bb");

    node=librdf_model_get_target(model, subject, predicate);
    librdf_free_node(subject);
    librdf_free_node(predicate);
    if(!node) {
      endTest(0, " Failed to get target\n");
    } else {
      print_node(stdout, node);
      librdf_free_node(node);
      endTest(1, "\n");
    }
  }


  /***** Test 16 *****/
  startTest(16, " Exec:  TARGETS  aa bb \n");
  {
    subject=librdf_new_node_from_uri_string(world, (const unsigned char*)"aa");
    predicate=librdf_new_node_from_uri_string(world, (const unsigned char*)"bb");

    iterator=librdf_model_get_targets(model, subject, predicate);
    librdf_free_node(subject);
    librdf_free_node(predicate);
    if(!iterator) {
      endTest(0, " Failed to get targets\n");
    } else {
      print_nodes(stdout, iterator);
      endTest(1, "\n");
    }
  }


  /***** Test 17 *****/
  startTest(17, " Exec:  REMOVE aa bb1 cc \n");
  {
    subject=librdf_new_node_from_uri_string(world, (const unsigned char*)"aa");
    predicate=librdf_new_node_from_uri_string(world, (const unsigned char*)"bb1");
    object=librdf_new_node_from_uri_string(world, (const unsigned char*)"cc");
    statement=librdf_new_statement(world);
    librdf_statement_set_subject(statement, subject);
    librdf_statement_set_predicate(statement, predicate);
    librdf_statement_set_object(statement, object);

    if(librdf_model_context_remove_statement(model, context_node, statement))
       endTest(0, " failed to remove triple from the graph\n");
    else
       endTest(1, " removed triple from the graph\n");

    librdf_free_statement(statement);
  }


  /***** Test 18 *****/
  query_cmd=(char *)"CONSTRUCT {?s ?p ?o} FROM <http://red> WHERE {?s ?p ?o}";
  startTest(18, " Exec:  QUERY \"%s\" \n", query_cmd);
  {
    query=librdf_new_query(world, (char *)"vsparql", NULL, (const unsigned char *)query_cmd, NULL);

    if(!(results=librdf_model_query_execute(model, query))) {
      endTest(0, " Query of model with '%s' failed\n", query_cmd);
      librdf_free_query(query);
      query=NULL;
    } else {
      stream=librdf_query_results_as_stream(results);

      if(!stream) {
        endTest(0, " QUERY returned no results (NULL stream)\n");
      } else {
        librdf_node* ctxt=NULL;
        count=0;
        while(!librdf_stream_end(stream)) {
          librdf_statement *stmt=librdf_stream_get_object(stream);  /*returns SHARED pointer */
          ctxt=(librdf_node*)librdf_stream_get_context(stream);
          if(!stmt) {
              endTest(0, " librdf_stream_next returned NULL\n");
              break;
          }

          fputs("Matched triple: ", stdout);
          librdf_statement_print(stmt, stdout);
          if(ctxt) {
              fputs(" with context ", stdout);
              librdf_node_print(ctxt, stdout);
          }
          fputc('\n', stdout);

          count++;
          librdf_stream_next(stream);
        }
       librdf_free_stream(stream);

        endTest(1, " matching triples: %d\n", count);
        librdf_free_query_results(results);
      }
    }
    librdf_free_query(query);
  }


  /***** Test 19 *****/
  query_cmd=(char *)"SELECT * WHERE {graph <http://red> { ?s ?p ?o }}";
  startTest(19, " Exec1:  QUERY_AS_BINDINGS \"%s\" \n", query_cmd);
  {
    query=librdf_new_query(world, (char *)"vsparql", NULL, (const unsigned char *)query_cmd, NULL);

    if(!(results=librdf_model_query_execute(model, query))) {
        endTest(0, " Query of model with '%s' failed\n", query_cmd);
        librdf_free_query(query);
        query=NULL;
    } else {

        raptor_iostream *iostr;
        librdf_query_results_formatter *formatter;

        fprintf(stderr, "**: Formatting query result as '%s':\n", results_format);

        iostr = raptor_new_iostream_to_file_handle(librdf_world_get_raptor(world), stdout);
        formatter = librdf_new_query_results_formatter2(results, results_format,
                                                        NULL /* mime type */,
                                                        NULL /* format_uri */);

        base_uri = librdf_new_uri(world, (const unsigned char*)"http://example.org/");
        
        librdf_query_results_formatter_write(iostr, formatter, results, base_uri);
        librdf_free_query_results_formatter(formatter);
        raptor_free_iostream(iostr);
        librdf_free_uri(base_uri);

        endTest(1, "\n");
        librdf_free_query_results(results);
    }
    librdf_free_query(query);
  }


  /***** Test 20 *****/
  query_cmd=(char *)"SELECT * WHERE {graph <http://red> { ?s ?p ?o }}";
  startTest(20, " Exec2:  QUERY_AS_BINDINGS \"%s\" \n", query_cmd);
  {
    query=librdf_new_query(world, (char *)"vsparql", NULL, (const unsigned char *)query_cmd, NULL);

    if(!(results=librdf_model_query_execute(model, query))) {
       endTest(0, " Query of model with '%s' failed\n", query_cmd);
       librdf_free_query(query);
       query=NULL;
    } else {
       if(print_query_results(world, model, results))
         endTest(0, "\n");
       else
         endTest(1, "\n");

       librdf_free_query_results(results);
    }
    librdf_free_query(query);
  }

  getTotal();


  if(transactions)
    librdf_model_transaction_commit(model);

  librdf_free_node(context_node);
  librdf_free_node(context_node);
  librdf_free_hash(options);
  librdf_free_model(model);
  librdf_free_storage(storage);

  librdf_free_world(world);

#ifdef LIBRDF_MEMORY_DEBUG
  librdf_memory_report(stderr);
#endif
	
  /* keep gcc -Wall happy */
  return(0);
}
예제 #14
0
UT_Error IE_Imp_OpenDocument::_handleRDFStreams ()
{
#ifndef WITH_REDLAND
    return UT_OK;
#else
    UT_Error error = UT_OK;
    
    UT_DEBUGMSG(("IE_Imp_OpenDocument::_handleRDFStreams()\n"));

    // // DEBUG.
    // {
    //     PD_DocumentRDFHandle rdf = getDoc()->getDocumentRDF();
    //     PD_DocumentRDFMutationHandle m = rdf->createMutation();
    //     m->add( PD_URI("http://www.example.com/foo#bar" ),
    //             PD_URI("http://www.example.com/foo#bar" ),
    //             PD_Object("http://www.example.com/foo#bar" ) );
    //     m->commit();
    //     rdf->dumpModel("added foo");
    // }
    

    
    RDFArguments args;
    librdf_model* model = args.model;

    // check if we can load a manifest.rdf file
    GsfInput* pRdfManifest = gsf_infile_child_by_name(m_pGsfInfile, "manifest.rdf");
    if (pRdfManifest)
    {
        UT_DEBUGMSG(("IE_Imp_OpenDocument::_handleRDFStreams() have manifest.rdf\n"));
        error = _loadRDFFromFile( pRdfManifest, "manifest.rdf", &args );
        g_object_unref (G_OBJECT (pRdfManifest));
        if (error != UT_OK)
            return error;
    }

    // find other RDF/XML files referenced in the manifest
    const char* query_string = ""
        "prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \n"
        "prefix odf: <http://docs.oasis-open.org/opendocument/meta/package/odf#> \n"
        "prefix odfcommon: <http://docs.oasis-open.org/opendocument/meta/package/common#> \n"
        "select ?subj ?fileName \n"
        " where { \n"
        "  ?subj rdf:type odf:MetaDataFile . \n"
        "  ?subj odfcommon:path ?fileName  \n"
        " } \n";

    librdf_uri*   base_uri = 0;
    librdf_query* query = librdf_new_query( args.world, "sparql", 0,
                                            (unsigned char*)query_string,
                                            base_uri );
    librdf_query_results* results = librdf_query_execute( query, model );

    if( !results )
    {
        // Query failed is a failure to execute the SPARQL,
        // in which case there might be results but we couldn't find them
        UT_DEBUGMSG(("IE_Imp_OpenDocument::_handleRDFStreams() SPARQL query to find auxillary RDF/XML files failed! q:%p\n", query ));
        error = UT_ERROR;
    }
    else
    {
        UT_DEBUGMSG(("IE_Imp_OpenDocument::_handleRDFStreams() aux RDF/XML file count:%d\n",
                     librdf_query_results_get_count( results )));

        // parse auxillary RDF/XML files too
        for( ; !librdf_query_results_finished( results ) ;
             librdf_query_results_next( results ))
        {
            librdf_node* fnNode = librdf_query_results_get_binding_value_by_name
                ( results, "fileName" );
            UT_DEBUGMSG(("_handleRDFStreams() fnNode:%p\n", fnNode ));
            std::string fn = toString(fnNode);
        
            UT_DEBUGMSG(("_handleRDFStreams() loading auxilary RDF/XML file from:%s\n",
                         fn.c_str()));
            GsfInput* pAuxRDF = gsf_infile_child_by_name(m_pGsfInfile, fn.c_str());
            if (pAuxRDF) {
                error = _loadRDFFromFile( pAuxRDF, fn.c_str(), &args );
                g_object_unref (G_OBJECT (pAuxRDF));
                if( error != UT_OK )
                    break;
            } else {
                UT_ASSERT_HARMLESS(UT_SHOULD_NOT_HAPPEN);
                return UT_ERROR;
            }
        }
        librdf_free_query_results( results );
    }
    librdf_free_query( query );

    UT_DEBUGMSG(("_handleRDFStreams() error:%d model.sz:%d\n",
                 error, librdf_model_size( model )));
    if( error != UT_OK )
    {
        return error;
    }
    
    // convert the redland model into native AbiWord RDF triples
    {
        PD_DocumentRDFHandle rdf = getDoc()->getDocumentRDF();
        PD_DocumentRDFMutationHandle m = rdf->createMutation();
        librdf_statement* statement = librdf_new_statement( args.world );
        librdf_stream* stream = librdf_model_find_statements( model, statement );

		while (!librdf_stream_end(stream))
        {
            librdf_statement* current = librdf_stream_get_object( stream );

            int objectType = PD_Object::OBJECT_TYPE_URI;
            
            std::string xsdType = "";
            if( librdf_node_is_blank( librdf_statement_get_object( current )))
            {
                objectType = PD_Object::OBJECT_TYPE_BNODE;
            }
            if( librdf_node_is_literal( librdf_statement_get_object( current )))
            {
                objectType = PD_Object::OBJECT_TYPE_LITERAL;
                if( librdf_uri* u = librdf_node_get_literal_value_datatype_uri(
                        librdf_statement_get_object( current )))
                {
                    xsdType = toString(u);
                }
            }

            if( DEBUG_RDF_IO )
            {
                UT_DEBUGMSG(("_handleRDFStreams() adding s:%s p:%s o:%s rotv:%d otv:%d ots:%s\n",
                             toString( librdf_statement_get_subject( current )).c_str(),
                             toString( librdf_statement_get_predicate( current )).c_str(),
                             toString( librdf_statement_get_object( current )).c_str(),
                             librdf_node_get_type(librdf_statement_get_object( current )),
                             objectType,
                             xsdType.c_str()
                                ));
            }
            
            m->add( PD_URI( toString( librdf_statement_get_subject( current ))),
                    PD_URI( toString( librdf_statement_get_predicate( current ))),
                    PD_Object( toString( librdf_statement_get_object( current )), objectType, xsdType ));

            // m->add( PD_URI( toString( librdf_statement_get_subject( current ))),
            //         PD_URI( toString( librdf_statement_get_predicate( current ))),
            //         PD_Object( toString( librdf_statement_get_object( current )),
            //                    objectType,
            //                    xsdType ));

            librdf_stream_next(stream);
        }
        
        librdf_free_stream( stream );
        librdf_free_statement( statement );
        // m->add( PD_URI("http://www.example.com/foo#bar" ),
        //         PD_URI("http://www.example.com/foo#bar" ),
        //         PD_Object("http://www.example.com/foo#bar" ) );
        m->commit();
    }

    if( DEBUG_RDF_IO )
    {
        getDoc()->getDocumentRDF()->dumpModel("Loaded RDF from ODF file");
    }
    return error;
#endif
}
예제 #15
0
int
main(int argc, char *argv[]) 
{
  const char *program=librdf_basename((const char*)argv[0]);
  const char *test_serializer_types[]={"rdfxml", "ntriples", NULL};
  int i;
  const char *type;
  unsigned char *string;
  size_t string_length;
  librdf_world *world;
  librdf_storage *storage;
  librdf_model* model;
  librdf_uri* base_uri;
  librdf_statement* statement;
  librdf_serializer* serializer;
  librdf_parser* parser;
  librdf_stream* stream;
  FILE *fh;
  struct stat st_buf;

  world=librdf_new_world();
  librdf_world_open(world);

  librdf_world_set_logger(world, &LogData, log_handler);

  for(i=0; (type=test_serializer_types[i]); i++) {
    fprintf(stderr, "%s: Trying to create new %s serializer\n", program, type);
    serializer=librdf_new_serializer(world, type, NULL, NULL);
    if(!serializer) {
      fprintf(stderr, "%s: Failed to create new serializer type %s\n", program, type);
      continue;
    }
    
    fprintf(stderr, "%s: Freeing serializer\n", program);
    librdf_free_serializer(serializer);
  }
  

  storage=librdf_new_storage(world, NULL, NULL, NULL);
  model=librdf_new_model(world, storage, NULL);

  /* ERROR: Subject URI is bad UTF-8 */
  statement=librdf_new_statement_from_nodes(world,
    librdf_new_node_from_uri_string(world, (const unsigned char*)"http://example.org/foo\xfc"),
    librdf_new_node_from_uri_string(world, (const unsigned char*)"http://example.org/bar"),
    librdf_new_node_from_literal(world, (const unsigned char*)"blah", NULL, 0));

  librdf_model_add_statement(model, statement);
  librdf_free_statement(statement);

  /* ERROR: Predicate URI is not serializable */
  statement=librdf_new_statement_from_nodes(world,
    librdf_new_node_from_uri_string(world, (const unsigned char*)"http://example.org/foo"),
    librdf_new_node_from_uri_string(world, (const unsigned char*)"http://bad.example.org/"),
    librdf_new_node_from_literal(world, (const unsigned char*)"blah", NULL, 0));

  librdf_model_add_statement(model, statement);
  librdf_free_statement(statement);

  /* ERROR: Object literal is bad UTF-8 */
  statement=librdf_new_statement_from_nodes(world,
    librdf_new_node_from_uri_string(world, (const unsigned char*)"http://example.org/foo"),
    librdf_new_node_from_uri_string(world, (const unsigned char*)"http://example.org/abc"),
    librdf_new_node_from_literal(world, (const unsigned char*)"\xfc", NULL, 0));

  librdf_model_add_statement(model, statement);
  librdf_free_statement(statement);

  serializer=librdf_new_serializer(world, "rdfxml", NULL, NULL);
  base_uri=librdf_new_uri(world, (const unsigned char*)"http://example.org/base#");

  string=librdf_serializer_serialize_model_to_counted_string(serializer,
                                                             base_uri, model,
                                                             &string_length);
#define EXPECTED_BAD_STRING_LENGTH 382
  if(string_length != EXPECTED_BAD_STRING_LENGTH) {
    fprintf(stderr, "%s: Serialising model to RDF/XML returned string '%s' size %d, expected %d\n", program, string,
            (int)string_length, EXPECTED_BAD_STRING_LENGTH);
    return 1;
  }

  if(string)
    free(string);

  librdf_free_uri(base_uri); base_uri=NULL;
  librdf_free_model(model); model=NULL;
  librdf_free_storage(storage); storage=NULL;
  

  if(LogData.errors != EXPECTED_ERRORS) {
    fprintf(stderr, "%s: Serialising to RDF/XML returned %d errors, expected %d\n", program,
            LogData.errors, EXPECTED_ERRORS);
    return 1;
  }

  if(LogData.warnings != EXPECTED_WARNINGS) {
    fprintf(stderr, "%s: Serialising to RDF/XML returned %d warnings, expected %d\n", program,
            LogData.warnings, EXPECTED_WARNINGS);
    return 1;
  }
  

  /* Good model to serialize */
  storage=librdf_new_storage(world, NULL, NULL, NULL);
  model=librdf_new_model(world, storage, NULL);

  parser=librdf_new_parser(world, SYNTAX_TYPE, NULL, NULL);
  if(!parser) {
    fprintf(stderr, "%s: Failed to create new parser type %s\n", program, 
            SYNTAX_TYPE);
    return 1;
  }

  fprintf(stderr, "%s: Adding %s string content\n", program, SYNTAX_TYPE);
  if(librdf_parser_parse_string_into_model(parser, 
                                           (const unsigned char*)SYNTAX_CONTENT,
                                           NULL /* no base URI*/, 
                                           model)) {
    fprintf(stderr, "%s: Failed to parse RDF from %s string into model\n", 
            SYNTAX_TYPE, program);
    return 1;
  }
  librdf_free_parser(parser);
  

  fprintf(stderr, "%s: Serializing stream to a string\n", program);

  stream=librdf_model_as_stream(model);
  string_length=0;
  string=librdf_serializer_serialize_stream_to_counted_string(serializer,
                                                              NULL, stream,
                                                              &string_length);
#define EXPECTED_GOOD_STRING_LENGTH 668
  if(string_length != EXPECTED_GOOD_STRING_LENGTH) {
    fprintf(stderr, "%s: Serialising stream to RDF/XML returned string '%s' size %d, expected %d\n", program, string,
            (int)string_length, EXPECTED_GOOD_STRING_LENGTH);
    return 1;
  }
  librdf_free_stream(stream);

  if(string)
    free(string);


  fprintf(stderr, "%s: Serializing stream to a file handle\n", program);

  stream=librdf_model_as_stream(model);

#define FILENAME "test.rdf"
  fh=fopen(FILENAME, "w");
  if(!fh) {
    fprintf(stderr, "%s: Failed to fopen for writing '%s' - %s\n",
            program, FILENAME, strerror(errno));
    return 1;
  }
  librdf_serializer_serialize_stream_to_file_handle(serializer, fh, NULL, 
                                                    stream);
  fclose(fh);
  stat(FILENAME, &st_buf);
  
  if((int)st_buf.st_size != EXPECTED_GOOD_STRING_LENGTH) {
    fprintf(stderr, "%s: Serialising stream to file handle returned file '%s' of size %d bytes, expected %d\n", program, FILENAME, (int)st_buf.st_size, 
            EXPECTED_GOOD_STRING_LENGTH);
    return 1;
  }
  unlink(FILENAME);
  
  librdf_free_stream(stream);


  librdf_free_serializer(serializer); serializer=NULL;
  librdf_free_model(model); model=NULL;
  librdf_free_storage(storage); storage=NULL;


  librdf_free_world(world);
  
  /* keep gcc -Wall happy */
  return(0);
}
예제 #16
0
void run_query(librdf_world* world, librdf_model* model, const std::string& q)
{
    librdf_stream* strm;

    std::cout << "** Query: " << q << std::endl;

    librdf_uri* uri1 =
	librdf_new_uri(world, (const unsigned char*) "http://bunchy.org");

    if (uri1 == 0)
	throw std::runtime_error("Couldn't parse URI");
    
    librdf_uri* uri2 =
	librdf_new_uri(world, (const unsigned char*) "http://bunchy.org");
    if (uri2 == 0)
	throw std::runtime_error("Couldn't parse URI");
    
    librdf_query* qry =
	librdf_new_query(world, "sparql", uri1,
			 (const unsigned char*) q.c_str(),
			 uri2);
    
    librdf_free_uri(uri1);
    librdf_free_uri(uri2);
    
    if (qry == 0)
	throw std::runtime_error("Couldn't parse query.");
    
    librdf_query_results* results = librdf_query_execute(qry, model);
    if (results == 0)
	throw std::runtime_error("Couldn't execute query");
    
    librdf_free_query(qry);
    
    strm = librdf_query_results_as_stream(results);
    if (strm == 0)
	throw std::runtime_error("Couldn't stream results");
    
    librdf_serializer* srl = librdf_new_serializer(world, "ntriples",
						   0, 0);
    if (srl == 0)
	throw std::runtime_error("Couldn't create serialiser");
    
    size_t len;
    
    unsigned char* out =
	librdf_serializer_serialize_stream_to_counted_string(srl, 0,
							     strm, &len);
    
    std::cout << "--------------------------------------------------------"
	      << std::endl;
    write(1, out, len);
    std::cout << "--------------------------------------------------------"
	      << std::endl;
    
    free(out);
    
    librdf_free_serializer(srl);

    librdf_free_stream(strm);
    
    librdf_free_query_results(results);
    
}
예제 #17
0
int main(int argc, char** argv)
{

    try {

	/*********************************************************************/
	/* Initialise                                                        */
	/*********************************************************************/

	std::cout << "** Initialise" << std::endl;

	librdf_world* world = librdf_new_world();

	if (world == 0)
	    throw std::runtime_error("Didn't get world");

	librdf_storage* storage =
	    librdf_new_storage(world, STORE, STORE_NAME, "new='yes'");
	if (storage == 0)
	    throw std::runtime_error("Didn't get storage");

	librdf_model* model =
	    librdf_new_model(world, storage, 0);
	if (model == 0)
	    throw std::runtime_error("Couldn't construct model");

	/*********************************************************************/
	/* Create in-memory model                                            */
	/*********************************************************************/

	std::cout << "** Create in-memory model" << std::endl;

	librdf_storage* mstorage =
	    librdf_new_storage(world, "memory", 0, 0);
	if (storage == 0)
	    throw std::runtime_error("Didn't get storage");

	librdf_model* mmodel =
	    librdf_new_model(world, mstorage, 0);
	if (model == 0)
	    throw std::runtime_error("Couldn't construct model");

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

	    char sbuf[256];
	    char obuf[256];

	    sprintf(sbuf, "http://gaffer.test/number#%d", i);
	    sprintf(obuf, "http://gaffer.test/number#%d", i+1);

	    librdf_node *s =
		librdf_new_node_from_uri_string(world,
						(const unsigned char *) sbuf);

	    librdf_node *p =
		librdf_new_node_from_uri_string(world,
						(const unsigned char *)
						"http://gaffer.test/number#is_before");

	    librdf_node *o =
		librdf_new_node_from_uri_string(world,
						(const unsigned char*) obuf);

	    librdf_statement* st = librdf_new_statement_from_nodes(world,
								   s, p, o);

	    librdf_model_add_statement(mmodel, st);

	    librdf_free_statement(st);

	}

	/*********************************************************************/
	/* Size                                                              */
	/*********************************************************************/

	std::cout << "** Model size is " << librdf_model_size(model)
		  << std::endl;

	/*********************************************************************/
	/* Add statement                                                     */
	/*********************************************************************/


	std::cout << "** Add statement" << std::endl;

	const char* fred = "http://gaffer.test/#fred";
	const char* is_a = "http://gaffer.test/#is_a";
	const char* cat = "http://gaffer.test/#cat";

	librdf_node *s =
	    librdf_new_node_from_uri_string(world,
					    (const unsigned char *) fred);
	librdf_node *p =
	    librdf_new_node_from_uri_string(world,
					    (const unsigned char *) is_a);
	librdf_node *o =
	    librdf_new_node_from_uri_string(world,
					    (const unsigned char *) cat);

	librdf_statement* st = librdf_new_statement_from_nodes(world, s, p, o);

	librdf_model_add_statement(model, st);

	/*********************************************************************/
	/* Add memory model statements                                       */
	/*********************************************************************/

	std::cout << "** Add statements" << std::endl;

	librdf_stream* strm = librdf_model_as_stream(mmodel);
	if (strm == 0)
	    throw std::runtime_error("Couldn't get memory stream");
	
	int ret = librdf_model_add_statements(model, strm);
	if (ret != 0)
	    throw std::runtime_error("Couldn't add_statements");

	librdf_free_stream(strm);

	librdf_free_model(mmodel);

	librdf_free_storage(mstorage);

	/*********************************************************************/
	/* Run queries                                                       */
	/*********************************************************************/

	run_query(world, model, query_string8);
	run_query(world, model, query_string1);
	run_query(world, model, query_string2);
	run_query(world, model, query_string3);
	run_query(world, model, query_string4);
	run_query(world, model, query_string5);
	run_query(world, model, query_string6);
	run_query2(world, model, query_string7);

	/*********************************************************************/
	/* Remove statement                                                  */
	/*********************************************************************/

	std::cout << "** Remove statements" << std::endl;

	librdf_model_remove_statement(model, st);
	
	/*********************************************************************/
	/* Serialise                                                         */
	/*********************************************************************/

	std::cout << "** Serialise" << std::endl;

	strm = librdf_model_as_stream(model);
	if (strm == 0)
	    throw std::runtime_error("Couldn't get model as stream");

	librdf_serializer* srl = librdf_new_serializer(world, "ntriples",
						       0, 0);
	if (srl == 0)
	    throw std::runtime_error("Couldn't create serialiser");

	size_t len;
	unsigned char* out =
	    librdf_serializer_serialize_stream_to_counted_string(srl, 0,
								 strm, &len);

	std::cout << "--------------------------------------------------------"
		  << std::endl;
	write(1, out, len);
	std::cout << "--------------------------------------------------------"
		  << std::endl;

	free(out);

	librdf_free_stream(strm);

	librdf_free_serializer(srl);
	
	/*********************************************************************/
	/* Cleanup                                                           */
	/*********************************************************************/

	librdf_free_statement(st);

	librdf_free_model(model);

	librdf_free_storage(storage);

	librdf_free_world(world);

    } catch (std::exception& e) {

	std::cerr << e.what() << std::endl;

    }

}
예제 #18
0
static librdf_stream*
librdf_storage_trees_serialise_range(librdf_storage* storage, librdf_statement* range)
{
  librdf_storage_trees_instance* context=(librdf_storage_trees_instance*)storage->instance;
  librdf_storage_trees_serialise_stream_context* scontext;
  librdf_stream* stream;
  int filter = 0;
  
  scontext=(librdf_storage_trees_serialise_stream_context*)LIBRDF_CALLOC(librdf_storage_trees_serialise_stream_context, 1, sizeof(librdf_storage_trees_serialise_stream_context));
  if(!scontext)
    return NULL;
    
  scontext->iterator = NULL;

  /* ?s ?p ?o */
  if (!range || (!range->subject && !range->predicate && !range->object)) {
    scontext->iterator=librdf_avltree_get_iterator_start(storage->world, context->graph->spo_tree,
        NULL, NULL);
    if (range) {
      librdf_free_statement(range);
      range=NULL;
    }
  /* s ?p o */
  } else if (range->subject && !range->predicate && range->object) {
    if (context->index_sop)
      scontext->iterator=librdf_avltree_get_iterator_start(storage->world, context->graph->sop_tree,
        range, librdf_storage_trees_avl_free);
	else
		filter=1;
  /* s _ _ */
  } else if (range->subject) {
    scontext->iterator=librdf_avltree_get_iterator_start(storage->world, context->graph->spo_tree,
        range, librdf_storage_trees_avl_free);
  /* ?s _ o */
  } else if (range->object) {
    if (context->index_ops)
      scontext->iterator=librdf_avltree_get_iterator_start(storage->world, context->graph->ops_tree,
          range, librdf_storage_trees_avl_free);
	else
		filter=1;
  /* ?s p ?o */
  } else { /* range->predicate != NULL */
    if (context->index_pso)
      scontext->iterator=librdf_avltree_get_iterator_start(storage->world, context->graph->pso_tree,
          range, librdf_storage_trees_avl_free);
	else
		filter=1;
  }
    
  /* If filter is set, we're missing the required index.
   * Iterate over the entire model and filter the stream.
   * (With a fully indexed store, this will never happen) */
  if (filter) {
    scontext->iterator=librdf_avltree_get_iterator_start(storage->world, context->graph->spo_tree,
        range, librdf_storage_trees_avl_free);
  }

#ifdef RDF_STORAGE_TREES_WITH_CONTEXTS
  scontext->context_node=NULL;
#endif

  if(!scontext->iterator) {
    LIBRDF_FREE(librdf_storage_trees_serialise_stream_context, scontext);
    return librdf_new_empty_stream(storage->world);
  }
  
  scontext->storage=storage;
  librdf_storage_add_reference(scontext->storage);

  stream=librdf_new_stream(storage->world,
                           (void*)scontext,
                           &librdf_storage_trees_serialise_end_of_stream,
                           &librdf_storage_trees_serialise_next_statement,
                           &librdf_storage_trees_serialise_get_statement,
                           &librdf_storage_trees_serialise_finished);
  
  if(!stream) {
    librdf_storage_trees_serialise_finished((void*)scontext);
    return NULL;
  }

  if(filter) {
    if(librdf_stream_add_map(stream, &librdf_stream_statement_find_map, NULL, (void*)range)) {
      /* error - stream_add_map failed */
      librdf_free_stream(stream);
      stream=NULL;
    }
  }
  
  return stream;  
}
예제 #19
0
int 
print_query_results(librdf_world* world, librdf_model* model, librdf_query_results *results)
{
  int i;
  char *name;
  librdf_stream* stream;
  librdf_serializer* serializer;
  const char *query_graph_serializer_syntax_name="rdfxml";

  if(librdf_query_results_is_bindings(results)) {
    fprintf(stdout, ": Query returned bindings results:\n");

    while(!librdf_query_results_finished(results)) {
      fputs("result: [", stdout);
      for(i=0; i<librdf_query_results_get_bindings_count(results); i++) {
	librdf_node *value=librdf_query_results_get_binding_value(results, i);
	name=(char*)librdf_query_results_get_binding_name(results, i);

	if(i>0)
	fputs(", ", stdout);
	fprintf(stdout, "%s=", name);
	if(value) {
	  librdf_node_print(value, stdout);
	  librdf_free_node(value);
	} else
	fputs("NULL", stdout);
      }
      fputs("]\n", stdout);

      librdf_query_results_next(results);
    }
    fprintf(stdout, ": Query returned %d results\n", librdf_query_results_get_count(results));
  } else if(librdf_query_results_is_boolean(results)) {
    fprintf(stdout, ": Query returned boolean result: %s\n", librdf_query_results_get_boolean(results) ? "true" : "false");
  } else if(librdf_query_results_is_graph(results)) {
    librdf_storage* tmp_storage;
    librdf_model* tmp_model;

    tmp_storage=librdf_new_storage(world, NULL, NULL, NULL);
    tmp_model=librdf_new_model(world, tmp_storage, NULL);

    fprintf(stdout, ": Query returned graph result:\n");

    stream=librdf_query_results_as_stream(results);
    if(!stream) {
      fprintf(stderr, ": Failed to get query results graph\n");
      return -1;
    }
    librdf_model_add_statements(tmp_model, stream);
    librdf_free_stream(stream);

    fprintf(stdout, ": Total %d triples\n", librdf_model_size(model));

    serializer=librdf_new_serializer(world, query_graph_serializer_syntax_name, NULL, NULL);
    if(!serializer) {
      fprintf(stderr, ": Failed to create serializer type %s\n", query_graph_serializer_syntax_name);
      return -1;
    }

    librdf_serializer_serialize_model_to_file_handle(serializer, stdout, NULL, tmp_model);
    librdf_free_serializer(serializer);
    librdf_free_model(tmp_model);
    librdf_free_storage(tmp_storage);
  } else {
    fprintf(stdout, ": Query returned unknown result format\n");
    return -1;
  }
  return 0;
}
예제 #20
0
파일: rdf_stream.c 프로젝트: herc/librdf
int
main(int argc, char *argv[]) 
{
  librdf_statement *statement;
  librdf_stream* stream;
  const char *program=librdf_basename((const char*)argv[0]);
  librdf_world *world;
  librdf_uri* prefix_uri;
  librdf_node* nodes[STREAM_NODES_COUNT];
  int i;
  librdf_iterator* iterator;
  int count;
  
  world=librdf_new_world();
  librdf_world_open(world);

  prefix_uri=librdf_new_uri(world, (const unsigned char*)NODE_URI_PREFIX);
  if(!prefix_uri) {
    fprintf(stderr, "%s: Failed to create prefix URI\n", program);
    return(1);
  }

  for(i=0; i < STREAM_NODES_COUNT; i++) {
    unsigned char buf[2];
    buf[0]='a'+i;
    buf[1]='\0';
    nodes[i]=librdf_new_node_from_uri_local_name(world, prefix_uri, buf);
    if(!nodes[i]) {
      fprintf(stderr, "%s: Failed to create node %i (%s)\n", program, i, buf);
      return(1);
    }
  }
  
  fprintf(stdout, "%s: Creating static node iterator\n", program);
  iterator = librdf_node_new_static_node_iterator(world, nodes, STREAM_NODES_COUNT);
  if(!iterator) {
    fprintf(stderr, "%s: Failed to create static node iterator\n", program);
    return(1);
  }

  statement=librdf_new_statement_from_nodes(world,
                                            librdf_new_node_from_uri_string(world, (const unsigned char*)"http://example.org/resource"),
                                            librdf_new_node_from_uri_string(world, (const unsigned char*)"http://example.org/property"),
                                            NULL);
  if(!statement) {
    fprintf(stderr, "%s: Failed to create statement\n", program);
    return(1);
  }

  fprintf(stdout, "%s: Creating stream from node iterator\n", program);
  stream=librdf_new_stream_from_node_iterator(iterator, statement, LIBRDF_STATEMENT_OBJECT);
  if(!stream) {
    fprintf(stderr, "%s: Failed to createstatic  node stream\n", program);
    return(1);
  }
  

  /* This is to check that the stream_from_node_iterator code
   * *really* takes a copy of what it needs from statement 
   */
  fprintf(stdout, "%s: Freeing statement\n", program);
  librdf_free_statement(statement);


  fprintf(stdout, "%s: Listing static node stream\n", program);
  count=0;
  while(!librdf_stream_end(stream)) {
    librdf_statement* s_statement=librdf_stream_get_object(stream);
    if(!s_statement) {
      fprintf(stderr, "%s: librdf_stream_current returned NULL when not end of stream\n", program);
      return(1);
    }

    fprintf(stdout, "%s: statement %d is: ", program, count);
    librdf_statement_print(s_statement, stdout);
    fputc('\n', stdout);
    
    librdf_stream_next(stream);
    count++;
  }

  if(count != STREAM_NODES_COUNT) {
    fprintf(stderr, "%s: Stream returned %d statements, expected %d\n", program,
            count, STREAM_NODES_COUNT);
    return(1);
  }

  fprintf(stdout, "%s: stream from node iterator worked ok\n", program);


  fprintf(stdout, "%s: Freeing stream\n", program);
  librdf_free_stream(stream);


  fprintf(stdout, "%s: Freeing nodes\n", program);
  for (i=0; i<STREAM_NODES_COUNT; i++) {
    librdf_free_node(nodes[i]);
  }

  librdf_free_uri(prefix_uri);
  
  librdf_free_world(world);
  
  /* keep gcc -Wall happy */
  return(0);
}
예제 #21
0
int
main(int argc, char *argv[]) 
{
  librdf_world* world;
  librdf_storage *storage, *new_storage;
  librdf_model *model, *new_model;
  librdf_stream *stream;
  char *program=argv[0];
  char *name;
  char *new_name;
  int count;

  if(argc < 2 || argc >3) {
    fprintf(stderr, "USAGE: %s: <Redland BDB name> [new DB name]\n", program);
    return(1);
  }

  name=argv[1];

  if(argc < 3) {
    new_name=librdf_heuristic_gen_name(name);
    if(!new_name) {
      fprintf(stderr, "%s: Failed to create new name from '%s'\n", program,
              name);
      return(1);
    }
  } else {
    new_name=argv[2];
  }
  
  fprintf(stderr, "%s: Upgrading DB '%s' to '%s'\n", program, name, new_name);

  world=librdf_new_world();
  librdf_world_open(world);

  storage=librdf_new_storage(world, "hashes", name, 
                             "hash-type='bdb',dir='.',write='no',new='no'");
  if(!storage) {
    fprintf(stderr, "%s: Failed to open old storage '%s'\n", program, name);
    return(1);
  }

  new_storage=librdf_new_storage(world, "hashes", new_name,
                                 "hash-type='bdb',dir='.',write='yes',new='yes'");
  if(!storage) {
    fprintf(stderr, "%s: Failed to create new storage '%s'\n", program, new_name);
    return(1);
  }

  model=librdf_new_model(world, storage, NULL);
  if(!model) {
    fprintf(stderr, "%s: Failed to create model for '%s'\n", program, name);
    return(1);
  }

  new_model=librdf_new_model(world, new_storage, NULL);
  if(!new_model) {
    fprintf(stderr, "%s: Failed to create new model for '%s'\n", program, new_name);
    return(1);
  }
  
  stream=librdf_model_as_stream(model);
  if(!stream) {
    fprintf(stderr, "%s: librdf_model_as_stream returned NULL stream\n", 
            program);
    return(1);
  } else {
    count=0;
    while(!librdf_stream_end(stream)) {
      librdf_statement *statement=librdf_stream_get_object(stream);
      if(!statement) {
        fprintf(stderr, "%s: librdf_stream_next returned NULL\n", program);
        break;
      }
      
      librdf_model_add_statement(new_model, statement);

      librdf_stream_next(stream);
      count++;
    }
    librdf_free_stream(stream);  
  }

      
  librdf_free_model(model);
  librdf_free_model(new_model);

  librdf_free_storage(storage);
  librdf_free_storage(new_storage);

  librdf_free_world(world);

  if(argc < 3)
    free(new_name);


#ifdef LIBRDF_MEMORY_DEBUG
  librdf_memory_report(stderr);
#endif
	
  /* keep gcc -Wall happy */
  return(0);
}