예제 #1
0
/**
 * librdf_storage_add_statements - Add a stream of statements to the storage
 * @storage: &librdf_storage object
 * @statement_stream: &librdf_stream of statements
 * 
 * Return value: non 0 on failure
 **/
int
librdf_storage_add_statements(librdf_storage* storage,
                              librdf_stream* statement_stream) 
{
  int status=0;
  
  LIBRDF_ASSERT_OBJECT_POINTER_RETURN_VALUE(storage, librdf_storage, 1);
  LIBRDF_ASSERT_OBJECT_POINTER_RETURN_VALUE(statement_stream, librdf_stream, 1);

  if(storage->factory->add_statements)
    return storage->factory->add_statements(storage, statement_stream);

  while(!librdf_stream_end(statement_stream)) {
    librdf_statement* statement=librdf_stream_get_object(statement_stream);

    if(statement)
      status=librdf_storage_add_statement(storage, statement);
    else
      status=1;

    if(status)
      break;

    librdf_stream_next(statement_stream);
  }
  
  return status;
}
예제 #2
0
파일: rdf_stream.c 프로젝트: herc/librdf
/**
 * librdf_stream_print:
 * @stream: the stream object
 * @fh: the FILE stream to print to
 *
 * Print the stream.
 *
 * This prints the remaining statements of the stream to the given
 * file handle.  Note that after this method is called the stream
 * will be empty so that librdf_stream_end() will always be true
 * and librdf_stream_next() will always return NULL.  The only
 * useful operation is to dispose of the stream with the
 * librdf_free_stream() destructor.
 * 
 * This method is for debugging and the format of the output should
 * not be relied on.
 *
 * @Deprecated: Use librdf_stream_write() to write to
 * #raptor_iostream which can be made to write to a string.  Use a
 * #librdf_serializer to write proper syntax formats.
 *
 **/
void
librdf_stream_print(librdf_stream *stream, FILE *fh)
{
  raptor_iostream *iostr;

  if(!stream)
    return;

  iostr = raptor_new_iostream_to_file_handle(stream->world->raptor_world_ptr, fh);
  if(!iostr)
    return;
  
  while(!librdf_stream_end(stream)) {
    librdf_statement* statement = librdf_stream_get_object(stream);
    librdf_node* context_node = librdf_stream_get_context2(stream);
    if(!statement)
      break;

    fputs("  ", fh);
    librdf_statement_write(statement, iostr);
    if(context_node) {
      fputs(" with context ", fh);
      librdf_node_print(context_node, fh);
    }
    fputs("\n", fh);

    librdf_stream_next(stream);
  }

  raptor_free_iostream(iostr);
}
예제 #3
0
/**
 * librdf_storage_context_add_statements - Add statements to a storage with a context
 * @storage: &librdf_storage object
 * @context: &librdf_node context
 * @stream: &librdf_stream stream object
 * 
 * If @context is NULL, this is equivalent to librdf_storage_add_statements
 *
 * Return value: Non 0 on failure
 **/
int
librdf_storage_context_add_statements(librdf_storage* storage, 
                                      librdf_node* context,
                                      librdf_stream* stream) 
{
  int status=0;
  
  LIBRDF_ASSERT_OBJECT_POINTER_RETURN_VALUE(storage, librdf_storage, 1);
  LIBRDF_ASSERT_OBJECT_POINTER_RETURN_VALUE(context, librdf_statement, 1);

  if(storage->factory->context_add_statements)
    return storage->factory->context_add_statements(storage, context, stream);

  if(!storage->factory->context_add_statement)
    return 1;
  
  if(!stream)
    return 1;

  while(!librdf_stream_end(stream)) {
    librdf_statement* statement=librdf_stream_get_object(stream);
    if(!statement)
      break;
    status=librdf_storage_context_add_statement(storage, context, statement);
    if(status)
      break;
    librdf_stream_next(stream);
  }

  return status;
}
예제 #4
0
파일: rdf_stream.c 프로젝트: herc/librdf
/**
 * librdf_stream_write:
 * @stream: the stream object
 * @iostr: the iostream to write to
 *
 * Write a stream of triples to an iostream in a debug format.
 *
 * This prints the remaining statements of the stream to the given
 * #raptor_iostream in a debug format.
 *
 * Note that after this method is called the stream will be empty so
 * that librdf_stream_end() will always be true and
 * librdf_stream_next() will always return NULL.  The only useful
 * operation is to dispose of the stream with the
 * librdf_free_stream() destructor.
 * 
 * This method is for debugging and the format of the output should
 * not be relied on.  In particular, when contexts are used the
 * result may be 4 nodes.
 *
 * Return value: non-0 on failure
 **/
int
librdf_stream_write(librdf_stream *stream, raptor_iostream *iostr)
{
  LIBRDF_ASSERT_OBJECT_POINTER_RETURN_VALUE(stream, librdf_stream, 1);
  LIBRDF_ASSERT_OBJECT_POINTER_RETURN_VALUE(iostr, raptor_iostream, 1);

  while(!librdf_stream_end(stream)) {
    librdf_statement* statement;
    librdf_node* context_node;

    statement = librdf_stream_get_object(stream);
    if(!statement)
      break;

    raptor_iostream_counted_string_write("  ", 2, iostr);
    if(librdf_statement_write(statement, iostr))
      return 1;
    
    context_node = librdf_stream_get_context2(stream);
    if(context_node) {
      raptor_iostream_counted_string_write(" with context ", 14, iostr);
      librdf_node_write(context_node, iostr);
    }
    raptor_iostream_counted_string_write(". \n", 3, iostr);

    librdf_stream_next(stream);
  }

  return 0;
}
예제 #5
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;
}
예제 #6
0
void
log_stream_prefix(request_rec *r, librdf_stream *s, const char* prefix) {
    librdf_statement *st;
    while (1) {
         st = librdf_stream_get_object(s);
         ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, "%s %s", prefix, librdf_statement_to_string(st));
         if (librdf_stream_next(s)) break;
    }
}
예제 #7
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;
}
예제 #8
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;
}
예제 #9
0
static void*
librdf_storage_stream_to_node_iterator_get_method(void* iterator, int flags) 
{
  librdf_storage_stream_to_node_iterator_context* context=(librdf_storage_stream_to_node_iterator_context*)iterator;
  librdf_node* node;
  librdf_statement* statement=librdf_stream_get_object(context->stream);

  if(!statement)
    return NULL;

  switch(flags) {
    case LIBRDF_ITERATOR_GET_METHOD_GET_OBJECT:

      switch(context->want) {
        case LIBRDF_STATEMENT_SUBJECT: /* SOURCES (subjects) */
          node=librdf_statement_get_subject(statement);
          break;

        case LIBRDF_STATEMENT_PREDICATE: /* ARCS (predicates) */
          node=librdf_statement_get_predicate(statement);
          break;

        case LIBRDF_STATEMENT_OBJECT: /* TARGETS (objects) */
          node=librdf_statement_get_object(statement);
          break;

        default: /* error */
          LIBRDF_ERROR2(statement->world, "Unknown statement part %d\n", context->want);
          node=NULL;
      }
      break;
      
    case LIBRDF_ITERATOR_GET_METHOD_GET_CONTEXT:
      node=(librdf_node*)librdf_stream_get_context(context->stream);
      break;
      
    default:
      LIBRDF_ERROR2(statement->world, "Unknown iterator method flag %d\n", flags);
      node=NULL;
  }
  
  return (void*)node;
}
예제 #10
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;
}
예제 #11
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;
}
예제 #12
0
static int
librdf_storage_trees_add_statements(librdf_storage* storage,
                                    librdf_stream* statement_stream)
{
  int status=0;

  for(; !librdf_stream_end(statement_stream); librdf_stream_next(statement_stream)) {
    librdf_statement* statement=librdf_stream_get_object(statement_stream);

    if (statement) {
      status=librdf_storage_trees_add_statement(storage, statement);
      if (status)
        break;
    } else {
      status=1;
      break;
    }
  }
  
  return status;
}
예제 #13
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;
}
예제 #14
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);
}
예제 #15
0
static int
librdf_storage_cassandra_add_statements(librdf_storage* storage,
                                     librdf_stream* statement_stream)
{


    librdf_storage_cassandra_instance* context;
    context = (librdf_storage_cassandra_instance*)storage->instance;

    CassBatch* batch = 0;

    const int batch_size = 10;
    int rows = 0;

    for(; !librdf_stream_end(statement_stream);
	librdf_stream_next(statement_stream)) {

	librdf_statement* statement;
	librdf_node* context_node;
    
	statement = librdf_stream_get_object(statement_stream);
	context_node = librdf_stream_get_context2(statement_stream);

	if(!statement) {
	    break;
	}

	char* s;
	char* p;
	char* o;
	char* c;
	statement_helper(storage, statement, context_node, &s, &p, &o, &c);

	if (batch == 0)
	    batch = cass_batch_new(CASS_BATCH_TYPE_LOGGED);

	char* query = "INSERT INTO rdf.spo (s, p, o) VALUES (?, ?, ?);";
	CassStatement* stmt = cass_statement_new(query, 3);
	cass_statement_bind_string(stmt, 0, s);
	cass_statement_bind_string(stmt, 1, p);
	cass_statement_bind_string(stmt, 2, o);
	cass_batch_add_statement(batch, stmt);
	cass_statement_free(stmt);

	query = "INSERT INTO rdf.pos (s, p, o) VALUES (?, ?, ?);";
	stmt = cass_statement_new(query, 3);
	cass_statement_bind_string(stmt, 0, s);
	cass_statement_bind_string(stmt, 1, p);
	cass_statement_bind_string(stmt, 2, o);
	cass_batch_add_statement(batch, stmt);
	cass_statement_free(stmt);

	query = "INSERT INTO rdf.osp (s, p, o) VALUES (?, ?, ?);";
	stmt = cass_statement_new(query, 3);
	cass_statement_bind_string(stmt, 0, s);
	cass_statement_bind_string(stmt, 1, p);
	cass_statement_bind_string(stmt, 2, o);
	cass_batch_add_statement(batch, stmt);
	cass_statement_free(stmt);

	free(s);
	free(p);
	free(o);

	if (++rows > batch_size) {
	    
	    CassFuture* future = cass_session_execute_batch(context->session,
							    batch);
	    cass_batch_free(batch);

	    CassError rc = cass_future_error_code(future);

	    if (rc != CASS_OK) {
		fprintf(stderr, "Cassandra: %s\n", cass_error_desc(rc));
		const char* msg;
		size_t msg_len;
		cass_future_error_message(future, &msg, &msg_len);
		fprintf(stderr, "Cassandra: %*s\n", msg_len, msg);
		cass_future_free(future);
		return -1;
	    }
    
	    cass_future_free(future);

	    batch = 0;

	}

    }
    
    if (batch) {
	    
	CassFuture* future = cass_session_execute_batch(context->session,
							batch);
	cass_batch_free(batch);
	
	CassError rc = cass_future_error_code(future);
	
	if (rc != CASS_OK) {
	    fprintf(stderr, "Cassandra: %s\n", cass_error_desc(rc));
	    const char* msg;
	    size_t msg_len;
	    cass_future_error_message(future, &msg, &msg_len);
	    fprintf(stderr, "Cassandra: %*s\n", msg_len, msg);
	    cass_future_free(future);
	    return -1;
	}
	
	cass_future_free(future);

    }

    return 0;

}
예제 #16
0
static rasqal_triple_parts
rasqal_redland_bind_match(struct rasqal_triples_match_s* rtm,
                          void *user_data,
                          rasqal_variable* bindings[4],
                          rasqal_triple_parts parts) 
{
  rasqal_redland_triples_match_context* rtmc=(rasqal_redland_triples_match_context*)rtm->user_data;
  rasqal_literal* l;
  librdf_statement* statement;
  rasqal_triple_parts result=(rasqal_triple_parts)0;
  librdf_world *world = rtmc->stream->world;

  statement=librdf_stream_get_object(rtmc->stream);
  if(!statement)
    return (rasqal_triple_parts)0;
  
#if defined(LIBRDF_DEBUG) && LIBRDF_DEBUG > 1
  LIBRDF_DEBUG1("  matched statement ");
  librdf_statement_print(statement, stderr);
  fputc('\n', stderr);
#endif

  /* set 1 or 2 variable values from the fields of statement */

  if(bindings[0] && (parts & RASQAL_TRIPLE_SUBJECT)) {
#if defined(LIBRDF_DEBUG) && LIBRDF_DEBUG > 1
    LIBRDF_DEBUG1("binding subject to variable\n");
#endif
    l = redland_node_to_rasqal_literal(world,
                                       librdf_statement_get_subject(statement));
    rasqal_variable_set_value(bindings[0], l);
    result= RASQAL_TRIPLE_SUBJECT;
  }

  if(bindings[1] && (parts & RASQAL_TRIPLE_PREDICATE)) {
    if(bindings[0] == bindings[1]) {
      /* check matching(?x, ?x, ...) / subject=predicate */
      if(!librdf_node_equals(librdf_statement_get_subject(statement),
                             librdf_statement_get_predicate(statement)))
        return (rasqal_triple_parts)0;
#if defined(LIBRDF_DEBUG) && LIBRDF_DEBUG > 1
      LIBRDF_DEBUG1("subject and predicate values match\n");
#endif
    } else {
#if defined(LIBRDF_DEBUG) && LIBRDF_DEBUG > 1
      LIBRDF_DEBUG1("binding predicate to variable\n");
#endif
      l = redland_node_to_rasqal_literal(world,
                                         librdf_statement_get_predicate(statement));
      rasqal_variable_set_value(bindings[1], l);
      result= (rasqal_triple_parts)(result | RASQAL_TRIPLE_PREDICATE);
    }
  }

  if(bindings[2] && (parts & RASQAL_TRIPLE_OBJECT)) {
    int bind=1;
    
    if(bindings[0] == bindings[2]) {
      /* check matching (?x, ..., ?x) / subject=object */
      if(!librdf_node_equals(librdf_statement_get_subject(statement),
                             librdf_statement_get_object(statement)))
        return (rasqal_triple_parts)0;
      bind=0;
#if defined(LIBRDF_DEBUG) && LIBRDF_DEBUG > 1
      LIBRDF_DEBUG1("subject and object values match\n");
#endif
    }
    if((bindings[1] == bindings[2]) && 
       !(bindings[0] == bindings[1])) {
      /* check matching (..., ?x, ?x) / predicate=object
       * Don't do this if matching (?x, ?x, ...) / subject=predicate
       * was already done since that would mean the match was (?x, ?x, ?x)
       */
      if(!librdf_node_equals(librdf_statement_get_predicate(statement),
                             librdf_statement_get_object(statement)))
        return (rasqal_triple_parts)0;
      bind=0;
#if defined(LIBRDF_DEBUG) && LIBRDF_DEBUG > 1
      LIBRDF_DEBUG1("predicate and object values match\n");
#endif
    }
    
    if(bind) {
#if defined(LIBRDF_DEBUG) && LIBRDF_DEBUG > 1
      LIBRDF_DEBUG1("binding object to variable\n");
#endif
      l = redland_node_to_rasqal_literal(world,
                                         librdf_statement_get_object(statement));
      rasqal_variable_set_value(bindings[2], l);
      result= (rasqal_triple_parts)(result | RASQAL_TRIPLE_OBJECT);
    }
  }

  /* Contexts */
  if(bindings[3] && (parts & RASQAL_TRIPLE_ORIGIN)) {
    int bind=1;
    librdf_node* context_node = librdf_stream_get_context2(rtmc->stream);
    
    if(bindings[0] == bindings[3]) {
      /* check matching (?x, ..., ...) in context ?x */
      if(!librdf_node_equals(librdf_statement_get_subject(statement),
                             context_node))
        return (rasqal_triple_parts)0;
      bind=0;
#if defined(LIBRDF_DEBUG) && LIBRDF_DEBUG > 1
      LIBRDF_DEBUG1("subject and context values match\n");
#endif
    }

    if(bindings[1] == bindings[3]) {
      /* check matching (..., ?x,  ...) in context ?x */
      if(!librdf_node_equals(librdf_statement_get_predicate(statement),
                             context_node))
        return (rasqal_triple_parts)0;
      bind=0;
#if defined(LIBRDF_DEBUG) && LIBRDF_DEBUG > 1
      LIBRDF_DEBUG1("predicate and context values match\n");
#endif
    }

    if(bindings[2] == bindings[3]) {
      /* check matching (..., ..., ?x) in context ?x */
      if(!librdf_node_equals(librdf_statement_get_object(statement),
                             context_node))
        return (rasqal_triple_parts)0;
      bind=0;
#if defined(LIBRDF_DEBUG) && LIBRDF_DEBUG > 1
      LIBRDF_DEBUG1("object and context values match\n");
#endif
    }

    if(bind) {
#if defined(LIBRDF_DEBUG) && LIBRDF_DEBUG > 1
      LIBRDF_DEBUG1("binding origin to variable\n");
#endif
      if(context_node)
        l = redland_node_to_rasqal_literal(world, context_node);
      else
        l=NULL;
      rasqal_variable_set_value(bindings[3], l);
      result= (rasqal_triple_parts)(result | RASQAL_TRIPLE_ORIGIN);
    }
  }

  return result;
}
예제 #17
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
}
예제 #18
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);
}
예제 #19
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);
}