Example #1
0
int
main(int argc, char *argv[])
{
#ifdef HAVE_RAPTOR
  raptor_world *world = NULL;
  raptor_parser* rdf_parser = NULL;
  unsigned char *uri_string;
  raptor_uri *uri, *base_uri;

  world = raptor_new_world();

  rdf_parser = raptor_new_parser(world, "ntriples");

  raptor_parser_set_statement_handler(rdf_parser, NULL, print_triple);

  uri_string = raptor_uri_filename_to_uri_string(argv[1]);
  uri = raptor_new_uri(world, uri_string);
  base_uri = raptor_uri_copy(uri);

  raptor_parser_parse_file(rdf_parser, uri, base_uri);

  raptor_free_parser(rdf_parser);

  raptor_free_uri(base_uri);
  raptor_free_uri(uri);
  raptor_free_memory(uri_string);

  raptor_free_world(world);
#endif

  return EXIT_SUCCESS;
}
Example #2
0
static unsigned char*
rasqal_raptor_generate_id_handler(void *user_data,
                                  unsigned char *user_bnodeid)
{
    rasqal_raptor_triples_source_user_data* rtsc;

    rtsc = (rasqal_raptor_triples_source_user_data*)user_data;

    if(user_bnodeid) {
        unsigned char *mapped_id;
        size_t user_bnodeid_len = strlen(RASQAL_GOOD_CAST(const char*, user_bnodeid));

        mapped_id = RASQAL_MALLOC(unsigned char*,
                                  rtsc->mapped_id_base_len + 1 + user_bnodeid_len + 1);
        memcpy(mapped_id, rtsc->mapped_id_base, rtsc->mapped_id_base_len);
        mapped_id[rtsc->mapped_id_base_len] = '_';
        memcpy(mapped_id + rtsc->mapped_id_base_len + 1,
               user_bnodeid, user_bnodeid_len + 1);

        raptor_free_memory(user_bnodeid);
        return mapped_id;
    }

    return rasqal_raptor_get_genid(rtsc->world, RASQAL_GOOD_CAST(const unsigned char*, "genid"), -1);
}
Example #3
0
DllExport int call_conv load_nquad_file(CTXTdecl)
{
	char *filename = p2c_string(reg_term(CTXTdecl 1));

	unsigned char *uri_string;
	raptor_uri *uri, *base_uri;

	world = raptor_new_world();

	rdf_parser = raptor_new_parser(world, "nquads");

	raptor_parser_set_statement_handler(rdf_parser, NULL, handle_term);

	uri_string = raptor_uri_filename_to_uri_string(filename);
	uri = raptor_new_uri(world, uri_string);
	base_uri = raptor_uri_copy(uri);

	raptor_parser_parse_file(rdf_parser, uri, base_uri);

	raptor_free_parser(rdf_parser);

	raptor_free_uri(base_uri);
	raptor_free_uri(uri);
	raptor_free_memory(uri_string);

	raptor_free_world(world);

	return 1;
}
Example #4
0
/*****
** Lee el archivo que contiene las tripletas RDF
** y hace el llamado a la funcion save_triple() para guardarlos
*****/
void rdf_database_read_file(rdf_database db, const char *file)
{
    raptor_world *world = NULL;
    unsigned char *uri_string;
    raptor_uri *uri, *base_uri;

    // parser
    world = raptor_new_world();
    rdf_parser = raptor_new_parser(world, "rdfxml");

    // seteo funcion handler para cada nodo
    raptor_parser_set_statement_handler(rdf_parser, (void*)db, save_triple);

    uri_string = raptor_uri_filename_to_uri_string(file);
    uri = raptor_new_uri(world, uri_string);
    base_uri = raptor_uri_copy(uri);

    // empieza parseo y guardado en memoria
    raptor_parser_parse_file(rdf_parser, uri, base_uri);

    // liberar ram
    raptor_free_parser(rdf_parser);
    raptor_free_uri(base_uri);
    raptor_free_uri(uri);
    raptor_free_memory(uri_string);
    raptor_free_world(world);
}
Example #5
0
static void
rasqal_query_write_sparql_uri(sparql_writer_context *wc,
                              raptor_iostream* iostr, raptor_uri* uri)
{
  size_t len;
  unsigned char* string;
  raptor_qname* qname;

  qname = raptor_new_qname_from_namespace_uri(wc->nstack, uri, 10);
  if(qname) {
    const raptor_namespace* nspace = raptor_qname_get_namespace(qname);
    if(!raptor_namespace_get_prefix(nspace))
      raptor_iostream_write_byte(':', iostr);
    raptor_qname_write(qname, iostr);
    raptor_free_qname(qname);
    return;
  }
  
  if(wc->base_uri)
    string = raptor_uri_to_relative_counted_uri_string(wc->base_uri, uri, &len);
  else
    string = raptor_uri_as_counted_string(uri, &len);

  raptor_iostream_write_byte('<', iostr);
  raptor_string_ntriples_write(string, len, '>', iostr);
  raptor_iostream_write_byte('>', iostr);

  if(wc->base_uri)
    raptor_free_memory(string);
}
Example #6
0
static unsigned char*
librdf_raptor_generate_id_handler(void *user_data,
                                  unsigned char *user_bnodeid)
{
  librdf_world* world = (librdf_world*)user_data;

  if(user_bnodeid && world->bnode_hash) {
    unsigned char *mapped_id;

    mapped_id = (unsigned char*)librdf_hash_get(world->bnode_hash,
                                                (const char*)user_bnodeid);
    if(!mapped_id) {
      mapped_id = librdf_world_get_genid(world);

      if(mapped_id &&
         librdf_hash_put_strings(world->bnode_hash,
                                 (char*)user_bnodeid, (char*)mapped_id)) {
        /* error -> free mapped_id and return NULL */
        LIBRDF_FREE(char*, mapped_id);
        mapped_id = NULL;
      }
    }
    /* always free passed in bnodeid */
    raptor_free_memory(user_bnodeid);

    return mapped_id;
  } else
    return librdf_world_get_genid(world);
}
Example #7
0
static raptor_uri *rdf_parser_path_to_uri(raptor_world* world,char* path) {
    unsigned char *uri_string;
    raptor_uri *uri;
    uri_string = raptor_uri_filename_to_uri_string(path);
    uri=raptor_new_uri(world,uri_string);
    raptor_free_memory(uri_string);
    return uri;
}
Example #8
0
static int
test_write_to_string(raptor_world *world,
                     const char* test_string, size_t test_string_len,
                     const unsigned int expected_bytes_count)
{
  raptor_iostream *iostr = NULL;
  unsigned long count;
  int rc = 0;
  void *string = NULL;
  size_t string_len;
  const char* const label="write iostream to a string";

  
#if defined(RAPTOR_DEBUG) && RAPTOR_DEBUG > 1
  fprintf(stderr, "%s: Testing %s\n", program, label);
#endif

  iostr = raptor_new_iostream_to_string(world, &string, &string_len, NULL);
  if(!iostr) {
    fprintf(stderr, "%s: Failed to create write iostream to string\n",
            program);
    rc = 1;
    goto tidy;
  }

  raptor_iostream_write_bytes(test_string, 1, test_string_len, iostr);
  raptor_iostream_write_byte('\n', iostr);
  
  count = raptor_iostream_tell(iostr);
  if(count != expected_bytes_count) {
    fprintf(stderr, "%s: %s wrote %d bytes, expected %d\n", program, label,
            (int)count, expected_bytes_count);
    rc = 1;
  }

  raptor_free_iostream(iostr); iostr = NULL;

  if(!string) {
    fprintf(stderr, "%s: %s failed to create a string\n", program, label);
    return 1;
  }
  if(string_len != count) {
    fprintf(stderr, "%s: %s created a string length %d, expected %d\n",
            program, label, (int)string_len, (int)count);
    return 1;
  }

  tidy:
  if(string)
    raptor_free_memory(string);
  if(iostr)
    raptor_free_iostream(iostr);
  
  if(rc)
    fprintf(stderr, "%s: FAILED Testing %s\n", program, label);
    
  return rc;
}
Example #9
0
/**
 * librdf_query_results_to_counted_string2:
 * @query_results: #librdf_query_results object
 * @name: name of syntax to format to
 * @mime_type: mime type of syntax to format to (or NULL)
 * @format_uri: URI of syntax to format to (or NULL)
 * @base_uri: Base URI of output formatted syntax (or NULL)
 * @length_p: Pointer to where to store length of string (or NULL)
 *
 * Turn a query results into a string.
 * 
 * A query results format can be named, have a mime type, or
 * identified by a URI, all of which are optional.  The default
 * query results format will be used if @name, @mime_type and
 * @format_uri are all NULL.
 *
 * librdf_query_results_formats_enumerate() returns information on
 * the known query results names, labels and URIs.
 *
 * The @base_uri may be used for as the base URI the generated
 * syntax, depending on the format.
 *
 * The returned string must be freed by the caller using
 * librdf_free_memory().
 *
 * Return value: new string value or NULL on failure
 **/
unsigned char*
librdf_query_results_to_counted_string2(librdf_query_results *query_results,
                                        const char *name,
                                        const char *mime_type,
                                        librdf_uri *format_uri,
                                        librdf_uri *base_uri,
                                        size_t *length_p)
{
  librdf_query_results_formatter *formatter;
  void *string=NULL;
  size_t string_length=0;
  raptor_iostream *iostr;
  int error=0;

  LIBRDF_ASSERT_OBJECT_POINTER_RETURN_VALUE(query_results, librdf_query_results, NULL);

  iostr = raptor_new_iostream_to_string(query_results->query->world->raptor_world_ptr,
                                        &string, &string_length, malloc);
  if(!iostr)
    return NULL;
              
  formatter = librdf_new_query_results_formatter2(query_results,
                                                  name, mime_type,
                                                  format_uri);
  if(!formatter) {
    error=1;
    goto tidy;
  }

  if(librdf_query_results_formatter_write(iostr, formatter,
                                          query_results, base_uri))
    error=1;

  librdf_free_query_results_formatter(formatter);

 tidy:
  raptor_free_iostream(iostr);

  /* string is available only after the iostream is finished
   * - clean it up here on error */
  if(error) {
    if(string) {
      raptor_free_memory(string);
      string=NULL;
    }
  }
  else if(length_p)
    *length_p = string_length;
  
  return (unsigned char *)string;
}
Example #10
0
static void raptor_rdfa_end_element(void *user_data,
                                    raptor_xml_element* xml_element)
{
  raptor_qname* qname = raptor_xml_element_get_name(xml_element);
  unsigned char* localname = raptor_qname_to_counted_name(qname, NULL);
  const raptor_namespace* qname_ns = raptor_qname_get_namespace(qname);

  if(qname_ns)
    end_element(user_data, (const char*)localname,
                (const char*)qname_ns->prefix,
                (const xmlChar*)raptor_uri_as_string(qname_ns->uri));
  else
    end_element(user_data, (const char*)localname, NULL, NULL);

  raptor_free_memory(localname);
}
Example #11
0
/**
 * librdf_new_uri_from_filename:
 * @world: Redland #librdf_world object
 * @filename: filename
 *
 * Constructor - create a new #librdf_uri object from a filename.
 *
 * Return value: a new #librdf_uri object or NULL on failure
 **/
librdf_uri*
librdf_new_uri_from_filename(librdf_world* world, const char *filename) {
  librdf_uri* new_uri;
  unsigned char *uri_string;

  librdf_world_open(world);

  if(!filename)
    return NULL;
  
  uri_string=raptor_uri_filename_to_uri_string(filename);
  if(!uri_string)
    return NULL;
  
  new_uri=librdf_new_uri(world, uri_string);
  raptor_free_memory(uri_string);
  return new_uri;
}
Example #12
0
turtle_input::turtle_input(const std::string& path) {
    raptor_world* world = raptor_new_world();
    raptor_parser* parser = raptor_new_parser(world, "turtle");

    unsigned char* uri_string;
    raptor_uri *uri, *base_uri;
    uri_string = raptor_uri_filename_to_uri_string(path.c_str());
    uri = raptor_new_uri(world, uri_string);
    base_uri = raptor_uri_copy(uri);

    std::pair<triples_t*, raptor_uri*> user_data(&triples_, base_uri);
    raptor_parser_set_statement_handler(parser, (void*)&user_data,
                                        &statement_handler);

    triples_.clear();
    raptor_parser_parse_file(parser, uri, base_uri);

    raptor_free_uri(base_uri);
    raptor_free_uri(uri);
    raptor_free_memory(uri_string);

    raptor_free_parser(parser);
    raptor_free_world(world);
}
Example #13
0
int
main(int argc, char **argv) {
  const char *program=rasqal_basename(argv[0]);
  rasqal_query *query = NULL;
  rasqal_query_results *results = NULL;
  raptor_uri *base_uri;
  unsigned char *data_string;
  unsigned char *uri_string;
  const char *query_language_name=QUERY_LANGUAGE;
  const char *query_format=QUERY_FORMAT;
  unsigned char *query_string;
  int count;
  rasqal_world *world;
  const char *data_file;
  
  world=rasqal_new_world();
  if(!world || rasqal_world_open(world)) {
    fprintf(stderr, "%s: rasqal_world init failed\n", program);
    return(1);
  }

  if((data_file = getenv("RDF_DATA_FILE"))) {
    /* got data from environment */
  } else {
    if(argc != 2) {
      fprintf(stderr, "USAGE: %s data-filename\n", program);
      return(1);
    }
    data_file = argv[1];
  }
    
  data_string = raptor_uri_filename_to_uri_string(data_file);
  query_string=(unsigned char*)RASQAL_MALLOC(cstring, strlen((const char*)data_string)+strlen(query_format)+1);
  sprintf((char*)query_string, query_format, data_string);
  raptor_free_memory(data_string);
  
  uri_string=raptor_uri_filename_to_uri_string("");
  base_uri = raptor_new_uri(world->raptor_world_ptr, uri_string);
  raptor_free_memory(uri_string);

  query=rasqal_new_query(world, query_language_name, NULL);
  if(!query) {
    fprintf(stderr, "%s: creating query in language %s FAILED\n", program,
            query_language_name);
    return(1);
  }

  printf("%s: preparing %s query\n", program, query_language_name);
  if(rasqal_query_prepare(query, query_string, base_uri)) {
    fprintf(stderr, "%s: %s query prepare FAILED\n", program, 
            query_language_name);
    return(1);
  }

  RASQAL_FREE(cstring, query_string);

  printf("%s: executing query #1\n", program);
  results=rasqal_query_execute(query);
  if(!results) {
    fprintf(stderr, "%s: query execution 1 FAILED\n", program);
    return(1);
  }

  count=0;
  while(results && !rasqal_query_results_finished(results)) {
    int i;
    for(i=0; i<rasqal_query_results_get_bindings_count(results); i++) {
      const unsigned char *name=rasqal_query_results_get_binding_name(results, i);
      rasqal_literal *value=rasqal_query_results_get_binding_value(results, i);

      printf("result %d: variable %s=", count+1, (char*)name);
      rasqal_literal_print(value, stdout);
      putchar('\n');
    }
    rasqal_query_results_next(results);
    count++;
  }
  if(results)
    rasqal_free_query_results(results);
  if(count != EXPECTED_RESULTS_COUNT) {
    fprintf(stderr, "%s: query execution 1 returned %d results, expected %d\n",
            program, count, EXPECTED_RESULTS_COUNT);
    return(1);
  }

  printf("%s: executing query #2\n", program);
  results = rasqal_query_execute(query);
  if(!results) {
    fprintf(stderr, "%s: query execution 2 FAILED\n", program);
    return(1);
  }

  count=0;
  while(results && !rasqal_query_results_finished(results)) {
    int i;
    for(i=0; i<rasqal_query_results_get_bindings_count(results); i++) {
      const unsigned char *name=rasqal_query_results_get_binding_name(results, i);
      rasqal_literal *value=rasqal_query_results_get_binding_value(results, i);

      printf("result %d: variable %s=", count+1, (char*)name);
      rasqal_literal_print(value, stdout);
      putchar('\n');
    }
    rasqal_query_results_next(results);
    count++;
  }
  if(results)
    rasqal_free_query_results(results);
  if(count != EXPECTED_RESULTS_COUNT) {
    fprintf(stderr, "%s: query execution 2 returned %d results, expected %d\n", 
            program, count, EXPECTED_RESULTS_COUNT);
    return(1);
  }

  printf("%s: executing query #3\n", program);
  results = rasqal_query_execute(query);
  if(!results) {
    fprintf(stderr, "%s: query execution 3 FAILED\n", program);
    return(1);
  }

  rasqal_free_query_results(results);

  printf("%s: executing query #4\n", program);
  results = rasqal_query_execute(query);
  if(!results) {
    fprintf(stderr, "%s: query execution 4 FAILED\n", program);
    return(1);
  }

  rasqal_free_query_results(results);

  rasqal_free_query(query);

  raptor_free_uri(base_uri);

  rasqal_free_world(world);

  return 0;
}
Example #14
0
int
main(int argc, char *argv[])
{
  raptor_world *world = NULL;
  raptor_parser* rdf_parser = NULL;
  unsigned char *uri_string;
  raptor_uri *uri;
  raptor_uri *base_uri;
  int rc = 0;
  int free_uri_string = 0;

  rdf_serializer = NULL;

  if(argc < 2 || argc > 3) {
    fprintf(stderr, "USAGE: %s RDF-FILE [BASE-URI]\n", program);
    rc = 1;
    goto tidy;
  }

  world = raptor_new_world();

  uri_string = (unsigned char*)argv[1];
  if(!access((const char*)uri_string, R_OK)) {
    uri_string = raptor_uri_filename_to_uri_string((char*)uri_string);
    uri = raptor_new_uri(world, uri_string);
    free_uri_string = 1;
  } else {
    uri = raptor_new_uri(world, (const unsigned char*)uri_string);
  }

  if(argc == 3) {
    char* base_uri_string = argv[2];
    base_uri = raptor_new_uri(world, (unsigned char*)(base_uri_string));
  } else {
    base_uri = raptor_uri_copy(uri);
  }

  rdf_parser = raptor_new_parser(world, "guess");

  raptor_world_set_log_handler(world, rdf_parser, to_ntriples_log_handler);

  raptor_parser_set_statement_handler(rdf_parser, NULL,
                                      to_ntriples_write_triple);

  rdf_serializer = raptor_new_serializer(world, "ntriples");

  raptor_serializer_start_to_file_handle(rdf_serializer, base_uri, stdout);
  raptor_parser_parse_file(rdf_parser, uri, base_uri);
  raptor_serializer_serialize_end(rdf_serializer);

  raptor_free_serializer(rdf_serializer);
  raptor_free_parser(rdf_parser);

  raptor_free_uri(base_uri);
  raptor_free_uri(uri);
  if(free_uri_string)
    raptor_free_memory(uri_string);

  raptor_free_world(world);

  tidy:
  if(warning_count)
    rc = 2;
  else if(error_count)
    rc = 1;

  return rc;
}
Example #15
0
rasqal_query_results*
rasqal_cmdline_read_results(rasqal_world* world,
                            raptor_world* raptor_world_ptr,
                            rasqal_query_results_type results_type,
                            raptor_iostream* result_iostr,
                            const char* result_filename,
                            const char* result_format_name)
{
  rasqal_query_results_formatter* qrf = NULL;
  unsigned char *query_results_base_uri_string = NULL;
  raptor_uri* query_results_base_uri = NULL;
  rasqal_query_results* results = NULL;
  int rc;

  query_results_base_uri_string = raptor_uri_filename_to_uri_string(result_filename);

  query_results_base_uri = raptor_new_uri(raptor_world_ptr,
                                          query_results_base_uri_string);
  raptor_free_memory(query_results_base_uri_string);

  results = rasqal_new_query_results2(world, NULL, results_type);
  if(!results)
    goto tidy_fail;

  if(result_format_name) {
    /* check name */
    if(!rasqal_query_results_formats_check2(world, result_format_name,
                               NULL /* uri */,
                               NULL /* mime type */,
                               RASQAL_QUERY_RESULTS_FORMAT_FLAG_READER))
      return NULL;
  } else {
    /* or use default */
    result_format_name = rasqal_world_guess_query_results_format_name(world,
                               NULL /* uri */,
                               NULL /* mime_type */,
                               NULL /* buffer */,
                               0,
                               (const unsigned char*)result_filename);
  }

  qrf = rasqal_new_query_results_formatter(world,
                                           result_format_name,
                                           NULL /* mime type */,
                                           NULL /* uri */);
  if(!qrf)
    goto tidy_fail;

  rc = rasqal_query_results_formatter_read(world, result_iostr,
                                           qrf, results,
                                           query_results_base_uri);
  rasqal_free_query_results_formatter(qrf); qrf = NULL;
  raptor_free_uri(query_results_base_uri); query_results_base_uri = NULL;
  if(rc)
    goto tidy_fail;

  return results;

  tidy_fail:
  if(results)
    rasqal_free_query_results(results);
  if(query_results_base_uri)
    raptor_free_uri(query_results_base_uri);

  return NULL;
}
Example #16
0
int
main(int argc, char *argv[])
{
    int query_from_string = 0;
    unsigned char *query_string = NULL;
    unsigned char *uri_string = NULL;
    int free_uri_string = 0;
    unsigned char *base_uri_string = NULL;
    rasqal_query *rq = NULL;
    rasqal_query_results *results;
    const char *ql_name = "sparql";
    char *ql_uri = NULL;
    int rc = 0;
    raptor_uri *uri = NULL;
    raptor_uri *base_uri = NULL;
    char *filename = NULL;
    char *p;
    int usage = 0;
    int help = 0;
    int quiet = 0;
    int count = 0;
    int dryrun = 0;
    raptor_sequence* data_graphs = NULL;
    const char *result_format = NULL;
    query_output_format output_format = QUERY_OUTPUT_UNKNOWN;
    rasqal_feature query_feature = (rasqal_feature)-1;
    int query_feature_value= -1;
    unsigned char* query_feature_string_value = NULL;
    rasqal_world *world;
    raptor_world* raptor_world_ptr = NULL;
#ifdef RASQAL_INTERNAL
    int store_results = -1;
#endif
    char* data_graph_parser_name = NULL;
    raptor_iostream* iostr = NULL;
    const unsigned char* service_uri_string = 0;
    raptor_uri* service_uri = NULL;

    program = argv[0];
    if((p = strrchr(program, '/')))
        program = p + 1;
    else if((p = strrchr(program, '\\')))
        program = p + 1;
    argv[0] = program;

    world = rasqal_new_world();
    if(!world || rasqal_world_open(world)) {
        fprintf(stderr, "%s: rasqal_world init failed\n", program);
        return(1);
    }

    raptor_world_ptr = rasqal_world_get_raptor(world);
    rasqal_world_set_log_handler(world, world, roqet_log_handler);

#ifdef STORE_RESULTS_FLAG
    /* This is for debugging only */
    if(1) {
        char* sr = getenv("RASQAL_DEBUG_STORE_RESULTS");
        if(sr)
            store_results = atoi(sr);
    }
#endif

    while (!usage && !help)
    {
        int c;

#ifdef HAVE_GETOPT_LONG
        int option_index = 0;

        c = getopt_long (argc, argv, GETOPT_STRING, long_options, &option_index);
#else
        c = getopt (argc, argv, GETOPT_STRING);
#endif
        if (c == -1)
            break;

        switch (c) {
        case 0:
        case '?': /* getopt() - unknown option */
            usage = 1;
            break;

        case 'c':
            count = 1;
            break;

        case 'd':
            output_format = QUERY_OUTPUT_UNKNOWN;
            if(optarg) {
                int i;

                for(i = 1; i <= QUERY_OUTPUT_LAST; i++)
                    if(!strcmp(optarg, query_output_format_labels[i][0])) {
                        output_format = (query_output_format)i;
                        break;
                    }

            }
            if(output_format == QUERY_OUTPUT_UNKNOWN) {
                int i;
                fprintf(stderr,
                        "%s: invalid argument `%s' for `" HELP_ARG(d, dump-query) "'\n",
                        program, optarg);
                for(i = 1; i <= QUERY_OUTPUT_LAST; i++)
                    fprintf(stderr,
                            "  %-12s for %s\n", query_output_format_labels[i][0],
                            query_output_format_labels[i][1]);
                usage = 1;
            }
            break;


        case 'e':
            if(optarg) {
                query_string = (unsigned char*)optarg;
                query_from_string = 1;
            }
            break;

        case 'f':
            if(optarg) {
                if(!strcmp(optarg, "help")) {
                    int i;

                    fprintf(stderr, "%s: Valid query features are:\n", program);
                    for(i = 0; i < (int)rasqal_get_feature_count(); i++) {
                        const char *feature_name;
                        const char *feature_label;
                        if(!rasqal_features_enumerate(world, (rasqal_feature)i,
                                                      &feature_name, NULL,
                                                      &feature_label)) {
                            const char *feature_type;
                            feature_type = (rasqal_feature_value_type((rasqal_feature)i) == 0) ? "" : " (string)";
                            fprintf(stderr, "  %-20s  %s%s\n", feature_name, feature_label,
                                    feature_type);
                        }
                    }
                    fputs("Features are set with `" HELP_ARG(f, feature) " FEATURE=VALUE or `-f FEATURE'\nand take a decimal integer VALUE except where noted, defaulting to 1 if omitted.\n", stderr);

                    rasqal_free_world(world);
                    exit(0);
                } else {
                    int i;
                    size_t arg_len = strlen(optarg);

                    for(i = 0; i < (int)rasqal_get_feature_count(); i++) {
                        const char *feature_name;
                        size_t len;

                        if(rasqal_features_enumerate(world, (rasqal_feature)i,
                                                     &feature_name, NULL, NULL))
                            continue;

                        len = strlen(feature_name);

                        if(!strncmp(optarg, feature_name, len)) {
                            query_feature = (rasqal_feature)i;
                            if(rasqal_feature_value_type(query_feature) == 0) {
                                if(len < arg_len && optarg[len] == '=')
                                    query_feature_value=atoi(&optarg[len + 1]);
                                else if(len == arg_len)
                                    query_feature_value = 1;
                            } else {
                                if(len < arg_len && optarg[len] == '=')
                                    query_feature_string_value = (unsigned char*)&optarg[len + 1];
                                else if(len == arg_len)
                                    query_feature_string_value = (unsigned char*)"";
                            }
                            break;
                        }
                    }

                    if(query_feature_value < 0 && !query_feature_string_value) {
                        fprintf(stderr, "%s: invalid argument `%s' for `" HELP_ARG(f, feature) "'\nTry '%s " HELP_ARG(f, feature) " help' for a list of valid features\n",
                                program, optarg, program);
                        usage = 1;
                    }
                }
            }
            break;

        case 'F':
            if(optarg) {
                if(!raptor_world_is_parser_name(raptor_world_ptr, optarg)) {
                    fprintf(stderr,
                            "%s: invalid parser name `%s' for `" HELP_ARG(F, format) "'\n\n",
                            program, optarg);
                    usage = 1;
                } else {
                    data_graph_parser_name = optarg;
                }
            }
            break;

        case 'h':
            help = 1;
            break;

        case 'n':
            dryrun = 1;
            break;

        case 'p':
            if(optarg)
                service_uri_string = (const unsigned char*)optarg;
            break;

        case 'r':
            if(optarg)
                result_format = optarg;
            break;

        case 'i':
            if(rasqal_language_name_check(world, optarg))
                ql_name = optarg;
            else {
                int i;

                fprintf(stderr,
                        "%s: invalid argument `%s' for `" HELP_ARG(i, input) "'\n",
                        program, optarg);
                fprintf(stderr, "Valid arguments are:\n");
                for(i = 0; 1; i++) {
                    const raptor_syntax_description* desc;
                    desc = rasqal_world_get_query_language_description(world, i);
                    if(desc == NULL)
                        break;

                    fprintf(stderr, "  %-18s for %s\n", desc->names[0], desc->label);
                }
                usage = 1;
            }
            break;

        case 'q':
            quiet = 1;
            break;

        case 's':
        case 'D':
        case 'G':
            if(optarg) {
                rasqal_data_graph *dg = NULL;
                rasqal_data_graph_flags type;

                type = (c == 's' || c == 'G') ? RASQAL_DATA_GRAPH_NAMED :
                       RASQAL_DATA_GRAPH_BACKGROUND;

                if(!strcmp((const char*)optarg, "-")) {
                    /* stdin: use an iostream not a URI data graph */
                    unsigned char* source_uri_string;
                    raptor_uri* iostr_base_uri = NULL;
                    raptor_uri* graph_name = NULL;

                    /* FIXME - get base URI from somewhere else */
                    source_uri_string = (unsigned char*)"file:///dev/stdin";

                    iostr_base_uri = raptor_new_uri(raptor_world_ptr, source_uri_string);
                    if(iostr_base_uri) {
                        iostr = raptor_new_iostream_from_file_handle(raptor_world_ptr,
                                stdin);
                        if(iostr)
                            dg = rasqal_new_data_graph_from_iostream(world,
                                    iostr, iostr_base_uri,
                                    graph_name,
                                    type,
                                    NULL,
                                    data_graph_parser_name,
                                    NULL);
                    }

                    if(base_uri)
                        raptor_free_uri(base_uri);
                } else if(!access((const char*)optarg, R_OK)) {
                    /* file: use URI */
                    unsigned char* source_uri_string;
                    raptor_uri* source_uri;
                    raptor_uri* graph_name = NULL;

                    source_uri_string = raptor_uri_filename_to_uri_string((const char*)optarg);
                    source_uri = raptor_new_uri(raptor_world_ptr, source_uri_string);
                    raptor_free_memory(source_uri_string);

                    if(type == RASQAL_DATA_GRAPH_NAMED)
                        graph_name = source_uri;

                    if(source_uri)
                        dg = rasqal_new_data_graph_from_uri(world,
                                                            source_uri,
                                                            graph_name,
                                                            type,
                                                            NULL, data_graph_parser_name,
                                                            NULL);

                    if(source_uri)
                        raptor_free_uri(source_uri);
                } else {
                    raptor_uri* source_uri;
                    raptor_uri* graph_name = NULL;

                    /* URI: use URI */
                    source_uri = raptor_new_uri(raptor_world_ptr,
                                                (const unsigned char*)optarg);
                    if(type == RASQAL_DATA_GRAPH_NAMED)
                        graph_name = source_uri;

                    if(source_uri)
                        dg = rasqal_new_data_graph_from_uri(world,
                                                            source_uri,
                                                            graph_name,
                                                            type,
                                                            NULL, data_graph_parser_name,
                                                            NULL);

                    if(source_uri)
                        raptor_free_uri(source_uri);
                }

                if(!dg) {
                    fprintf(stderr, "%s: Failed to create data graph for `%s'\n",
                            program, optarg);
                    return(1);
                }

                if(!data_graphs) {
                    data_graphs = raptor_new_sequence((raptor_data_free_handler)rasqal_free_data_graph,
                                                      NULL);

                    if(!data_graphs) {
                        fprintf(stderr, "%s: Failed to create data graphs sequence\n",
                                program);
                        return(1);
                    }
                }

                raptor_sequence_push(data_graphs, dg);
            }
            break;

        case 'W':
            if(optarg)
                warning_level = atoi(optarg);
            else
                warning_level = 0;
            rasqal_world_set_warning_level(world, warning_level);
            break;

        case 'E':
            ignore_errors = 1;
            break;

        case 'v':
            fputs(rasqal_version_string, stdout);
            fputc('\n', stdout);
            rasqal_free_world(world);
            exit(0);

#ifdef STORE_RESULTS_FLAG
        case STORE_RESULTS_FLAG:
            store_results = (!strcmp(optarg, "yes") || !strcmp(optarg, "YES"));
            break;
#endif

        }

    }

    if(!help && !usage) {
        if(service_uri_string) {
            if(optind != argc && optind != argc-1)
                usage = 2; /* Title and usage */
        } else if(query_string) {
            if(optind != argc && optind != argc-1)
                usage = 2; /* Title and usage */
        } else {
            if(optind != argc-1 && optind != argc-2)
                usage = 2; /* Title and usage */
        }
    }


    if(usage) {
        if(usage > 1) {
            fprintf(stderr, title_format_string, rasqal_version_string);
            fputs("Rasqal home page: ", stderr);
            fputs(rasqal_home_url_string, stderr);
            fputc('\n', stderr);
            fputs(rasqal_copyright_string, stderr);
            fputs("\nLicense: ", stderr);
            fputs(rasqal_license_string, stderr);
            fputs("\n\n", stderr);
        }
        fprintf(stderr, "Try `%s " HELP_ARG(h, help) "' for more information.\n",
                program);
        rasqal_free_world(world);

        exit(1);
    }

    if(help) {
        int i;

        printf(title_format_string, rasqal_version_string);
        puts("Run an RDF query giving variable bindings or RDF triples.");
        printf("Usage: %s [OPTIONS] <query URI> [base URI]\n", program);
        printf("       %s [OPTIONS] -e <query string> [base URI]\n", program);
        printf("       %s [OPTIONS] -p <SPARQL protocol service URI> -e <query string> [base URI]\n\n", program);

        fputs(rasqal_copyright_string, stdout);
        fputs("\nLicense: ", stdout);
        puts(rasqal_license_string);
        fputs("Rasqal home page: ", stdout);
        puts(rasqal_home_url_string);

        puts("\nNormal operation is to execute the query retrieved from URI <query URI>");
        puts("and print the results in a simple text format.");
        puts("\nMain options:");
        puts(HELP_TEXT("e", "exec QUERY      ", "Execute QUERY string instead of <query URI>"));
        puts(HELP_TEXT("p", "protocol URI    ", "Execute QUERY against a SPARQL protocol service URI"));
        puts(HELP_TEXT("i", "input LANGUAGE  ", "Set query language name to one of:"));
        for(i = 0; 1; i++) {
            const raptor_syntax_description* desc;

            desc = rasqal_world_get_query_language_description(world, i);
            if(!desc)
                break;

            printf("    %-15s         %s", desc->names[0], desc->label);
            if(!i)
                puts(" (default)");
            else
                putchar('\n');
        }

        puts(HELP_TEXT("r", "results FORMAT  ", "Set query results output format to one of:"));
        puts("    For variable bindings and boolean results:");
        puts("      simple                A simple text format (default)");

        for(i = 0; 1; i++) {
            const raptor_syntax_description* desc;

            desc = rasqal_world_get_query_results_format_description(world, i);
            if(!desc)
                break;

            if(desc->flags & RASQAL_QUERY_RESULTS_FORMAT_FLAG_WRITER)
                printf("      %-10s            %s\n", desc->names[0], desc->label);
        }

        puts("    For RDF graph results:");

        for(i = 0; 1; i++) {
            const raptor_syntax_description *desc;
            desc = raptor_world_get_parser_description(raptor_world_ptr, i);
            if(!desc)
                break;

            printf("      %-15s       %s", desc->names[0], desc->label);
            if(!i)
                puts(" (default)");
            else
                putchar('\n');
        }
        puts("\nAdditional options:");
        puts(HELP_TEXT("c", "count             ", "Count triples - no output"));
        puts(HELP_TEXT("d FORMAT", "dump-query FORMAT", HELP_PAD "Print the parsed query out in FORMAT:"));
        puts(HELP_TEXT("D URI", "data URI      ", "RDF data source URI"));
        for(i = 1; i <= QUERY_OUTPUT_LAST; i++)
            printf("      %-15s         %s\n", query_output_format_labels[i][0],
                   query_output_format_labels[i][1]);
        puts(HELP_TEXT("E", "ignore-errors     ", "Ignore error messages"));
        puts(HELP_TEXT("f FEATURE(=VALUE)", "feature FEATURE(=VALUE)", HELP_PAD "Set query features" HELP_PAD "Use `-f help' for a list of valid features"));
        puts(HELP_TEXT("F NAME", "format NAME  ", "Set data source format name (default: guess)"));
        puts(HELP_TEXT("G URI", "named URI     ", "RDF named graph data source URI"));
        puts(HELP_TEXT("h", "help              ", "Print this help, then exit"));
        puts(HELP_TEXT("n", "dryrun            ", "Prepare but do not run the query"));
        puts(HELP_TEXT("q", "quiet             ", "No extra information messages"));
        puts(HELP_TEXT("s URI", "source URI    ", "Same as `-G URI'"));
        puts(HELP_TEXT("v", "version           ", "Print the Rasqal version"));
        puts(HELP_TEXT("w", "walk-query        ", "Print query.  Same as '-d structure'"));
        puts(HELP_TEXT("W LEVEL", "warnings LEVEL", HELP_PAD "Set warning message LEVEL from 0: none to 100: all"));
#ifdef STORE_RESULTS_FLAG
        puts(HELP_TEXT_LONG("store-results BOOL", "DEBUG: Set store results yes/no BOOL"));
#endif
        puts("\nReport bugs to http://bugs.librdf.org/");

        rasqal_free_world(world);

        exit(0);
    }


    if(service_uri_string) {
        service_uri = raptor_new_uri(raptor_world_ptr, service_uri_string);
        if(optind == argc-1) {
            base_uri_string = (unsigned char*)argv[optind];
        }
    } else if(query_string) {
        if(optind == argc-1)
            base_uri_string = (unsigned char*)argv[optind];
    } else {
        if(optind == argc-1)
            uri_string = (unsigned char*)argv[optind];
        else {
            uri_string = (unsigned char*)argv[optind++];
            base_uri_string = (unsigned char*)argv[optind];
        }

        /* If uri_string is "path-to-file", turn it into a file: URI */
        if(!strcmp((const char*)uri_string, "-")) {
            if(!base_uri_string) {
                fprintf(stderr, "%s: A Base URI is required when reading from standard input.\n",
                        program);
                return(1);
            }

            uri_string = NULL;
        } else if(!access((const char*)uri_string, R_OK)) {
            filename = (char*)uri_string;
            uri_string = raptor_uri_filename_to_uri_string(filename);
            free_uri_string = 1;
        }

        if(uri_string) {
            uri = raptor_new_uri(raptor_world_ptr, uri_string);
            if(!uri) {
                fprintf(stderr, "%s: Failed to create URI for %s\n",
                        program, uri_string);
                return(1);
            }
        } else
            uri = NULL; /* stdin */
    }

    if(!base_uri_string) {
        if(uri)
            base_uri = raptor_uri_copy(uri);
    } else
        base_uri = raptor_new_uri(raptor_world_ptr, base_uri_string);

    if(base_uri_string && !base_uri) {
        fprintf(stderr, "%s: Failed to create URI for %s\n",
                program, base_uri_string);
        return(1);
    }


    if(service_uri_string) {
        /* NOP - nothing to do here */
    } else if(query_string) {
        /* NOP - already got it */
    } else if(!uri_string) {
        size_t read_len;

        query_string = (unsigned char*)calloc(FILE_READ_BUF_SIZE, 1);
        read_len = fread(query_string, FILE_READ_BUF_SIZE, 1, stdin);
        if(read_len < FILE_READ_BUF_SIZE) {
            if(ferror(stdin))
                fprintf(stderr, "%s: query string stdin read failed - %s\n",
                        program, strerror(errno));
            else
                fprintf(stderr, "%s: query string stdin read failed - no error\n",
                        program);
            rc = 1;
            goto tidy_setup;
        }

        query_from_string = 0;
    } else if(filename) {
        raptor_stringbuffer *sb = raptor_new_stringbuffer();
        size_t len;
        FILE *fh;
        unsigned char* buffer;

        fh = fopen(filename, "r");
        if(!fh) {
            fprintf(stderr, "%s: file '%s' open failed - %s",
                    program, filename, strerror(errno));
            rc = 1;
            goto tidy_setup;
        }

        buffer = (unsigned char*)malloc(FILE_READ_BUF_SIZE);

        while(!feof(fh)) {
            size_t read_len;

            read_len = fread((char*)buffer, 1, FILE_READ_BUF_SIZE, fh);
            if(read_len > 0)
                raptor_stringbuffer_append_counted_string(sb, buffer, read_len, 1);

            if(read_len < FILE_READ_BUF_SIZE) {
                if(ferror(fh)) {
                    fprintf(stderr, "%s: file '%s' read failed - %s\n",
                            program, filename, strerror(errno));
                    free(buffer);
                    fclose(fh);
                    rc = 1;
                    goto tidy_setup;
                }

                break;
            }
        }
        free(buffer);
        fclose(fh);

        len = raptor_stringbuffer_length(sb);
        query_string = (unsigned char*)malloc(len + 1);
        raptor_stringbuffer_copy_to_string(sb, query_string, len);
        raptor_free_stringbuffer(sb);
        query_from_string = 0;
    } else {
        raptor_www *www;

        www = raptor_new_www(raptor_world_ptr);
        if(www) {
            raptor_www_fetch_to_string(www, uri, (void**)&query_string, NULL, malloc);
            raptor_free_www(www);
        }

        if(!query_string || error_count) {
            fprintf(stderr, "%s: Retrieving query at URI '%s' failed\n",
                    program, uri_string);
            rc = 1;
            goto tidy_setup;
        }

        query_from_string = 0;
    }


    if(!quiet) {
        if(service_uri) {
            fprintf(stderr, "%s: Calling SPARQL service at URI %s", program,
                    service_uri_string);
            if(query_string)
                fprintf(stderr, " with query '%s'", query_string);

            if(base_uri_string)
                fprintf(stderr, " with base URI %s\n", base_uri_string);

            fputc('\n', stderr);
        } else if(query_from_string) {
            if(base_uri_string)
                fprintf(stderr, "%s: Running query '%s' with base URI %s\n", program,
                        query_string, base_uri_string);
            else
                fprintf(stderr, "%s: Running query '%s'\n", program,
                        query_string);
        } else if(filename) {
            if(base_uri_string)
                fprintf(stderr, "%s: Querying from file %s with base URI %s\n", program,
                        filename, base_uri_string);
            else
                fprintf(stderr, "%s: Querying from file %s\n", program, filename);
        } else if(uri_string) {
            if(base_uri_string)
                fprintf(stderr, "%s: Querying URI %s with base URI %s\n", program,
                        uri_string, base_uri_string);
            else
                fprintf(stderr, "%s: Querying URI %s\n", program, uri_string);
        }
    }



    if(service_uri) {
        /* Execute query remotely */
        if(!dryrun)
            results = roqet_call_sparql_service(world, service_uri, query_string,
                                                data_graphs,
                                                /* service_format */ NULL);
    } else {
        /* Execute query in this query engine (from URI or from -e QUERY) */
        rq = roqet_init_query(world,
                              ql_name, ql_uri, query_string,
                              base_uri,
                              query_feature, query_feature_value,
                              query_feature_string_value,
                              store_results,
                              data_graphs);

        if(!rq) {
            rc = 1;
            goto tidy_query;
        }

        if(output_format != QUERY_OUTPUT_UNKNOWN && !quiet)
            roqet_print_query(rq, raptor_world_ptr, output_format, base_uri);

        if(!dryrun) {
            results = rasqal_query_execute(rq);
        }

    }


    /* No results from dryrun */
    if(dryrun)
        goto tidy_query;

    if(!results) {
        fprintf(stderr, "%s: Query execution failed\n", program);
        rc = 1;
        goto tidy_query;
    }

    if(rasqal_query_results_is_bindings(results)) {
        if(result_format)
            rc = print_formatted_query_results(world, results,
                                               raptor_world_ptr, stdout,
                                               result_format, base_uri, quiet);
        else
            print_bindings_result_simple(results, stdout, quiet, count);
    } else if(rasqal_query_results_is_boolean(results)) {
        if(result_format)
            rc = print_formatted_query_results(world, results,
                                               raptor_world_ptr, stdout,
                                               result_format, base_uri, quiet);
        else
            print_boolean_result_simple(results, stdout, quiet);
    } else if(rasqal_query_results_is_graph(results)) {
        if(!result_format)
            result_format = DEFAULT_GRAPH_FORMAT;

        rc = print_graph_result(rq, results, raptor_world_ptr,
                                stdout, result_format, base_uri, quiet);
    } else {
        fprintf(stderr, "%s: Query returned unknown result format\n", program);
        rc = 1;
    }

    rasqal_free_query_results(results);

tidy_query:
    if(!query_from_string)
        free(query_string);

    if(rq)
        rasqal_free_query(rq);

tidy_setup:

    if(data_graphs)
        raptor_free_sequence(data_graphs);
    if(base_uri)
        raptor_free_uri(base_uri);
    if(uri)
        raptor_free_uri(uri);
    if(free_uri_string)
        raptor_free_memory(uri_string);
    if(iostr)
        raptor_free_iostream(iostr);
    if(service_uri)
        raptor_free_uri(service_uri);

    rasqal_free_world(world);

    if(error_count && !ignore_errors)
        return 1;

    if(warning_count && warning_level != 0)
        return 2;

    return (rc);
}
Example #17
0
int
main(int argc, char **argv) {
  const char *program=rasqal_basename(argv[0]);
  const char *query_language_name=QUERY_LANGUAGE;
  raptor_uri *base_uri;
  unsigned char *uri_string;
  int test_i;
  limit_test* test;
  int tests_failed_count=0;
  int single_shot= -1;
  int query_i;
  rasqal_world *world;
  
  world=rasqal_new_world();
  if(!world || rasqal_world_open(world)) {
    fprintf(stderr, "%s: rasqal_world init failed\n", program);
    return(1);
  }
  
  if(argc < 2 || argc > 3) {
    fprintf(stderr, "USAGE: %s data-filename [test number]\n", program);
    return(1);
  }
    
  if(argv[2])
    single_shot=atoi(argv[2]);
  
  uri_string=raptor_uri_filename_to_uri_string("");
  base_uri = raptor_new_uri(world->raptor_world_ptr, uri_string);
  raptor_free_memory(uri_string);

  for(query_i=0; query_i < NQUERIES; query_i++) {
    const char *query_format = limit_queries[query_i];
    int dynamic_limits = (strstr(query_format, "%s %s") != NULL);
    
    for(test_i=(single_shot >=0 ? single_shot : 0);
        (test=&limit_offset_tests[test_i]) && (test->expected_count >=0);
        test_i++) {
      int result_i;
      rasqal_query *query = NULL;
      rasqal_query_results *results = NULL;
      const char* expected_results;
      int test_ok=1;
      unsigned char *data_string;
      unsigned char *query_string;
      size_t qs_len;

#define LIM_OFF_BUF_SIZE 20
      data_string=raptor_uri_filename_to_uri_string(argv[1]);
      qs_len = strlen((const char*)data_string) + strlen(query_format) + (2 * LIM_OFF_BUF_SIZE);
      query_string = RASQAL_MALLOC(unsigned char*, qs_len + 1);

      if(dynamic_limits) {
        char lim[LIM_OFF_BUF_SIZE];
        char off[LIM_OFF_BUF_SIZE];
        if(test->limit >= 0)
          snprintf(lim, LIM_OFF_BUF_SIZE, "LIMIT %d", test->limit);
        else
          *lim = '\0';
        if(test->offset >= 0)
          snprintf(off, LIM_OFF_BUF_SIZE, "OFFSET %d", test->offset);
        else
          *off = '\0';
        IGNORE_FORMAT_NONLITERAL_START
        snprintf((char*)query_string, qs_len, query_format, data_string, lim, off);
        IGNORE_FORMAT_NONLITERAL_END
      }
      else {
        IGNORE_FORMAT_NONLITERAL_START
        snprintf((char*)query_string, qs_len, query_format, data_string);
        IGNORE_FORMAT_NONLITERAL_END
      }
      raptor_free_memory(data_string);

      query = rasqal_new_query(world, query_language_name, NULL);
      if(!query) {
        fprintf(stderr, "%s: creating query in language %s FAILED\n", program,
                query_language_name);
        return(1);
      }

#if defined(RASQAL_DEBUG) && RASQAL_DEBUG > 1
      fprintf(stderr, 
              "%s: preparing query %d test %d - %s\n", program, query_i, test_i,
              query_string);
#endif
      if(rasqal_query_prepare(query, query_string, base_uri)) {
        fprintf(stderr, "%s: query %d test %d prepare '%s' FAILED\n", program, 
                query_i, test_i, query_string);
        return(1);
      }

      if(!dynamic_limits) {
        rasqal_query_set_limit(query, test->limit);
        rasqal_query_set_offset(query, test->offset);
      }

#if defined(RASQAL_DEBUG) && RASQAL_DEBUG > 1
      fprintf(stderr, "%s: executing query %d test %d\n", program, query_i,
              test_i);
#endif
      results=rasqal_query_execute(query);
      if(!results) {
        fprintf(stderr, "%s: query %d test %d FAILED\n", program,
                query_i, test_i);
        return(1);
      }


      /* check results */
      expected_results=test->expected_results[query_i];

      result_i=0;
      tests_failed_count=0;
      while(results && !rasqal_query_results_finished(results)) {
        rasqal_literal *value;
        const char* str;
        char expected_str[2]={0,0};
        int failed=1;

        if(result_i < test->expected_count)
          expected_str[0]=expected_results[result_i];

        value=rasqal_query_results_get_binding_value(results, 0);
        if(value) {
          int error=0;
          str=(const char*)rasqal_literal_as_string_flags(value, 0, &error);
          if(!error && str) {
            size_t len=strlen(str);
            if(len == 1 && str[0] == expected_str[0])
              failed=0;
          }
        }
        if(failed) {
          fprintf(stderr,
                  "%s: query %d test %d result %d FAILED returning value '%s' expected value '%s'\n",
                  program, query_i, test_i, result_i, (str ? str: "NULL"),
                  expected_str);
          test_ok=0;
        }

        rasqal_query_results_next(results);
        result_i++;
      }
      if(results)
        rasqal_free_query_results(results);

      if(!test_ok) {
        fprintf(stderr, "%s: query %d test %d limit %d offset %d FAILED\n",
                program, query_i, test_i, test->limit, test->offset);
      } else {
        if(result_i != test->expected_count) {
          fprintf(stderr,
                  "%s: query %d test %d limit %d offset %d FAILED returned %d results, expected %d\n",
                  program, 
                  query_i, test_i, test->limit, test->offset, result_i,
                  test->expected_count);
          test_ok=0;
        }
      }


      if(!test_ok) {
        tests_failed_count++;
      } else {
#if defined(RASQAL_DEBUG) && RASQAL_DEBUG > 1
        fprintf(stderr, "%s: query %d test %d OK\n", program, query_i, test_i);
#endif
      }

      rasqal_free_query(query);

      RASQAL_FREE(char*, query_string);

      if(single_shot >=0)
        break;

    } /* end test loop */

  } /* end query loop */
Example #18
0
static void raptor_rdfa_start_element(void *user_data,
                                      raptor_xml_element *xml_element)
{
  raptor_qname* qname = raptor_xml_element_get_name(xml_element);
  int nb_attributes = raptor_xml_element_get_attributes_count(xml_element);
  raptor_qname** attrs = raptor_xml_element_get_attributes(xml_element);
  unsigned char* localname = raptor_qname_to_counted_name(qname, NULL);
  const raptor_namespace* qname_ns = raptor_qname_get_namespace(qname);
  int nb_namespaces = 0;
  const char** namespaces = NULL;
  int nb_defaulted = 0;
  char** attr = NULL;
  int i;
  const char* ns_name = NULL;
  const char* ns_uri = NULL;

  if(nb_attributes > 0) {
    /* Everything written into 'attr' is a shared pointer into
     * xml_element or contained objects - qnames, namespaces, uris
     * and values
     */
    attr = (char**)malloc(sizeof(char*) * (1 + (nb_attributes * 5)));
    for(i = 0; i < nb_attributes; i++) {
      const raptor_namespace* attr_ns = attrs[i]->nspace;
      char** attri = &attr[5 * i];
      /* 5 tuple: (localname, prefix, URI, value, end) */
      attri[0] = (char*)attrs[i]->local_name;
      attri[1] = attr_ns ? (char*)attr_ns->prefix : NULL;
      attri[2] = attr_ns ? (char*)raptor_uri_as_string(attr_ns->uri) : NULL;
      attri[3] = (char*)attrs[i]->value;
      attri[4] = attri[3] + attrs[i]->value_length;
    }
    attr[5 * i] = NULL;
  }

/*
 * @ctx:  the user data (XML parser context)
 * @localname:  the local name of the element
 * @prefix:  the element namespace prefix if available
 * @URI:  the element namespace name if available
 * @nb_namespaces:  number of namespace definitions on that node
 * @namespaces:  pointer to the array of prefix/URI pairs namespace definitions
 * @nb_attributes:  the number of attributes on that node
 * @nb_defaulted:  the number of defaulted attributes. The defaulted
 *                  ones are at the end of the array
 * @attributes:  pointer to the array of (localname/prefix/URI/value/end)
 *               attribute values.
 */
  if(qname_ns) {
    ns_name = (const char*)raptor_namespace_get_prefix(qname_ns);
    ns_uri = (const char*)raptor_uri_as_string(qname_ns->uri);
  }

  start_element(user_data, (const char*)localname,
                ns_name,
                ns_uri,
                nb_namespaces,
                (const char**)namespaces,
                nb_attributes,
                nb_defaulted,
                (const char**)attr);
  if(attr)
    free(attr);
  raptor_free_memory(localname);
}
Example #19
0
/**
 * Handles the start_element call
 */
static void start_element(void *parser_context, const char* name,
   const char* prefix, const char* URI, int nb_namespaces,
   const char** namespaces, int nb_attributes, int nb_defaulted,
   const char** attributes)
{
   rdfacontext* root_context = (rdfacontext*)parser_context;
   rdfalist* context_stack = (rdfalist*)root_context->context_stack;
   rdfacontext* context = rdfa_create_new_element_context(context_stack);
   char* xml_lang = NULL;
   const char* about_curie = NULL;
   char* about = NULL;
   const char* src_curie = NULL;
   char* src = NULL;
   const char* type_of_curie = NULL;
   rdfalist* type_of = NULL;
   const char* rel_curie = NULL;
   rdfalist* rel = NULL;
   const char* rev_curie = NULL;
   rdfalist* rev = NULL;
   const char* property_curie = NULL;
   rdfalist* property = NULL;
   const char* resource_curie = NULL;
   char* resource = NULL;
   const char* href_curie = NULL;
   char* href = NULL;
   char* content = NULL;
   const char* datatype_curie = NULL;
   char* datatype = NULL;

#ifdef LIBRDFA_IN_RAPTOR
   if(1) {
        raptor_parser* rdf_parser = (raptor_parser*)context->callback_data;
        raptor_sax2_update_document_locator(context->sax2,
                                            &rdf_parser->locator);
    }
#endif

   rdfa_push_item(context_stack, context, RDFALIST_FLAG_CONTEXT);

#if defined(DEBUG) && DEBUG > 0
   if(1) {
      int i;

      /* dump all arguments sent to this callback */
      fprintf(stdout, "DEBUG: SAX.startElementNs(%s", (char *) name);
      if (prefix == NULL)
          fprintf(stdout, ", NULL");
      else
          fprintf(stdout, ", %s", (char *) prefix);
      if (URI == NULL)
          fprintf(stdout, ", NULL");
      else
          fprintf(stdout, ", '%s'", (char *) URI);
      fprintf(stdout, ", %d", nb_namespaces);

      /* dump all namespaces */
      if (namespaces != NULL) {
          for (i = 0;i < nb_namespaces * 2;i++) {
              fprintf(stdout, ", xmlns");
              if (namespaces[i] != NULL)
                  fprintf(stdout, ":%s", namespaces[i]);
              i++;
              fprintf(stdout, "='%s'", namespaces[i]);
          }
      }

      /* dump all attributes */
      fprintf(stdout, ", %d, %d", nb_attributes, nb_defaulted);
      if (attributes != NULL) {
          for (i = 0;i < nb_attributes * 5;i += 5) {
              if (attributes[i + 1] != NULL)
                  fprintf(
                     stdout, ", %s:%s='", attributes[i + 1], attributes[i]);
              else
                  fprintf(stdout, ", %s='", attributes[i]);
              fprintf(stdout, "%.4s...', %d", attributes[i + 3],
                      (int)(attributes[i + 4] - attributes[i + 3]));
          }
      }
      fprintf(stdout, ")\n");
   }
#endif

   /* start the XML Literal text */
   if(context->xml_literal == NULL)
   {
      context->xml_literal = rdfa_replace_string(context->xml_literal, "<");
      context->xml_literal_size = 1;
   }
   else
   {
      context->xml_literal = rdfa_n_append_string(
         context->xml_literal, &context->xml_literal_size, "<", 1);
   }
   context->xml_literal = rdfa_n_append_string(
      context->xml_literal, &context->xml_literal_size,
      name, strlen(name));

   if(!context->xml_literal_namespaces_defined)
   {
      /* append namespaces to XML Literal */
#ifdef LIBRDFA_IN_RAPTOR
      raptor_namespace_stack* nstack = &context->sax2->namespaces;
      raptor_namespace* ns;
      raptor_namespace** ns_list = NULL;
      size_t ns_size;
#else
      void** umap = context->uri_mappings;
#endif
      char* umap_key = NULL;
      void* umap_value = NULL;

      /* if the namespaces are not defined, then neither is the xml:lang */
      context->xml_literal_xml_lang_defined = 0;

#ifdef LIBRDFA_IN_RAPTOR
      ns_size = 0;
      ns_list = raptor_namespace_stack_to_array(nstack, &ns_size);
      qsort((void*)ns_list, ns_size, sizeof(raptor_namespace*),
            raptor_nspace_compare);

      while(ns_size > 0)
#else
      while(*umap != NULL)
#endif
      {
         unsigned char insert_xmlns_definition = 1;
         const char* attr = NULL;

         /* get the next mapping to process */
#ifdef LIBRDFA_IN_RAPTOR
         ns=ns_list[--ns_size];

         umap_key = (char*)raptor_namespace_get_prefix(ns);
         if(!umap_key)
           umap_key=(char*)XMLNS_DEFAULT_MAPPING;
         umap_value = (char*)raptor_uri_as_string(raptor_namespace_get_uri(ns));
#else
         rdfa_next_mapping(umap++, &umap_key, &umap_value);
         umap++;
#endif

         /* check to make sure that the namespace isn't already
          * defined in the current element. */
         if(attributes != NULL)
         {
            const char** attrs = attributes;
            while((*attrs != NULL) && insert_xmlns_definition)
            {
               attr = *attrs++;

               /* if the attribute is a umap_key, skip the definition
                * of the attribute. */
               if(strcmp(attr, umap_key) == 0)
               {
                  insert_xmlns_definition = 0;
               }
            }
         }

         /* if the namespace isn't already defined on the element,
          * copy it to the XML Literal string. */
         if(insert_xmlns_definition)
         {
            /* append the namespace attribute to the XML Literal */
            context->xml_literal = rdfa_n_append_string(
               context->xml_literal, &context->xml_literal_size,
               " xmlns", strlen(" xmlns"));

            /* check to see if we're dumping the standard XHTML namespace or
             * a user-defined XML namespace */
            if(strcmp(umap_key, XMLNS_DEFAULT_MAPPING) != 0)
            {
               context->xml_literal = rdfa_n_append_string(
                  context->xml_literal, &context->xml_literal_size, ":", 1);
               context->xml_literal = rdfa_n_append_string(
                  context->xml_literal, &context->xml_literal_size,
                  umap_key, strlen(umap_key));
            }

            /* append the namespace value */
            context->xml_literal = rdfa_n_append_string(
               context->xml_literal, &context->xml_literal_size, "=\"", 2);
            context->xml_literal = rdfa_n_append_string(
               context->xml_literal, &context->xml_literal_size,
               (const char*)umap_value, strlen((char*)umap_value));
            context->xml_literal = rdfa_n_append_string(
               context->xml_literal, &context->xml_literal_size, "\"", 1);
         }

      } /* end while umap not NULL */
      context->xml_literal_namespaces_defined = 1;

#ifdef LIBRDFA_IN_RAPTOR
      if(ns_list)
        raptor_free_memory(ns_list);
#endif
   } /* end if namespaces inserted */

#ifdef LIBRDFA_IN_RAPTOR
   /* Raptor namespace code does this already */
#else
   /* 3. For backward compatibility, RDFa Processors should also permit the
    * definition of mappings via @xmlns. In this case, the value to be mapped
    * is set by the XML namespace prefix, and the value to map is the value of
    * the attribute - an IRI. (Note that prefix mapping via @xmlns is
    * deprecated, and may be removed in a future version of this
    * specification.) When xmlns is supported, such mappings must be processed
    * before processing any mappings from @prefix on the same element. */
   if(namespaces != NULL)
   {
      int ni;

      for(ni = 0; ni < nb_namespaces * 2; ni += 2)
      {
         const char* ns = namespaces[ni];
         const char* value = namespaces[ni + 1];
         /* Regardless of how the mapping is declared, the value to be mapped
          * must be converted to lower case, and the IRI is not processed in
          * any way; in particular if it is a relative path it must not be
          * resolved against the current base. */
         char* lcns = NULL;
         if(ns != NULL)
         {
            /* convert the namespace string to lowercase */
            unsigned int i;
            size_t ns_length = strlen(ns);
            lcns = (char*)malloc(ns_length + 1);
            for(i = 0; i <= ns_length; i++)
            {
               lcns[i] = tolower(ns[i]);
            }
         }

         /* update the URI mappings */
         rdfa_update_uri_mappings(context, lcns, value);

         if(lcns != NULL)
         {
            free(lcns);
         }
      }
   }
#endif

   /* detect the RDFa version of the document, if specified */
   if(attributes != NULL)
   {
      int ci;

      /* search for a version attribute */
      for(ci = 0; ci < nb_attributes * 5; ci += 5)
      {
         const char* attr;
         char* value;
         size_t value_length = 0;

         attr = attributes[ci];
         value_length = attributes[ci + 4] - attributes[ci + 3] + 1;

         if(strcmp(attr, "version") == 0)
         {
            /* append the attribute-value pair to the XML literal */
            value = (char*)malloc(value_length + 1);
            snprintf(value, value_length, "%s", attributes[ci + 3]);
            if(strstr(value, "RDFa 1.0") != NULL)
            {
               context->rdfa_version = RDFA_VERSION_1_0;
            }
            else if(strstr(value, "RDFa 1.1") != NULL)
            {
               context->rdfa_version = RDFA_VERSION_1_1;
            }

            free(value);
         }
      }
   }

#ifdef LIBRDFA_IN_RAPTOR
   if(context->sax2) 
   {
       /* Raptor handles xml:lang itself but not 'lang' */
       xml_lang = (char*)raptor_sax2_inscope_xml_language(context->sax2);
       xml_lang = rdfa_replace_string(NULL, xml_lang);
   }
#endif

   /* prepare all of the RDFa-specific attributes we are looking for.
    * scan all of the attributes for the RDFa-specific attributes */
   if(attributes != NULL)
   {
      int ci;

      if(context->rdfa_version == RDFA_VERSION_1_1)
      {
         /* process all vocab and prefix attributes */
         for(ci = 0; ci < nb_attributes * 5; ci += 5)
         {
            const char* attr;
            char* value;
            size_t value_length = 0;

            attr = attributes[ci];
            value_length = attributes[ci + 4] - attributes[ci + 3] + 1;

            /* append the attribute-value pair to the XML literal */
            value = (char*)malloc(value_length + 1);
            snprintf(value, value_length, "%s", attributes[ci + 3]);

            /* 2. Next the current element is examined for any change to the
             * default vocabulary via @vocab. */
            if(strcmp(attr, "vocab") == 0)
            {
               if(strlen(value) < 1)
               {
                  /* If the value is empty, then the local default vocabulary
                   * must be reset to the Host Language defined default
                   * (if any). */
                  free(context->default_vocabulary);
                  context->default_vocabulary = NULL;
               }
               else
               {
                  char* resolved_uri;
                  rdftriple* triple;

                  /* If @vocab is present and contains a value, the local
                   * default vocabulary is updated according to the
                   * section on CURIE and IRI Processing. */
                  resolved_uri = rdfa_resolve_uri(context, value);
                  context->default_vocabulary = rdfa_replace_string(
                     context->default_vocabulary, resolved_uri);

                  /* The value of @vocab is used to generate a triple */
                  triple = rdfa_create_triple(
                     context->base, "http://www.w3.org/ns/rdfa#usesVocabulary",
                     resolved_uri, RDF_TYPE_IRI, NULL, NULL);
                  context->default_graph_triple_callback(
                     triple, context->callback_data);

                  free(resolved_uri);
               }
            }
            else if(strcmp(attr, "prefix") == 0)
            {
               /* Mappings are defined via @prefix. */
               char* working_string = NULL;
               char* atprefix = NULL;
               char* iri = NULL;
               char* saveptr = NULL;

               working_string = rdfa_replace_string(working_string, value);

               /* Values in this attribute are evaluated from beginning to
                * end (e.g., left to right in typical documents). */
               atprefix = strtok_r(working_string, ":", &saveptr);
               while(atprefix != NULL)
               {
                  /* find the prefix and IRI mappings while skipping whitespace */
                  while((*saveptr == ' ' || *saveptr == '\n' ||
                     *saveptr == '\r' || *saveptr == '\t' || *saveptr == '\f' ||
                     *saveptr == '\v') && *saveptr != '\0')
                  {
                     saveptr++;
                  }
                  iri = strtok_r(NULL, RDFA_WHITESPACE, &saveptr);

                  /* update the prefix mappings */
                  rdfa_update_uri_mappings(context, atprefix, iri);

                  if(!saveptr)
                      break;

                  while((*saveptr == ' ' || *saveptr == '\n' ||
                     *saveptr == '\r' || *saveptr == '\t' || *saveptr == '\f' ||
                     *saveptr == '\v') && *saveptr != '\0')
                  {
                     saveptr++;
                  }

                  /* get the next prefix to process */
                  atprefix = strtok_r(NULL, ":", &saveptr);
               }

               free(working_string);
            }
            else if(strcmp(attr, "inlist") == 0)
            {
               context->inlist_present = 1;
            }
            free(value);
         }
      }

      /* resolve all of the other RDFa values */
      for(ci = 0; ci < nb_attributes * 5; ci += 5)
      {
         const char* attr;
         char* value;
         char* attrns;
         char* literal_text;
         size_t value_length = 0;

         attr = attributes[ci];
         attrns = (char*)attributes[ci + 1];
         value_length = attributes[ci + 4] - attributes[ci + 3] + 1;

         /* append the attribute-value pair to the XML literal */
         value = (char*)malloc(value_length + 1);
         literal_text = (char*)malloc(strlen(attr) + value_length + 5);
         snprintf(value, value_length, "%s", attributes[ci + 3]);

         sprintf(literal_text, " %s=\"%s\"", attr, value);
         context->xml_literal = rdfa_n_append_string(
            context->xml_literal, &context->xml_literal_size,
            literal_text, strlen(literal_text));
         free(literal_text);

         /* if xml:lang is defined, ensure that it is not overwritten */
         if(attrns != NULL && strcmp(attrns, "xml") == 0 &&
            strcmp(attr, "lang") == 0)
         {
            context->xml_literal_xml_lang_defined = 1;
         }

         /* process all of the RDFa attributes */
         if(strcmp(attr, "about") == 0)
         {
            about_curie = value;
            about = rdfa_resolve_curie(
               context, about_curie, CURIE_PARSE_ABOUT_RESOURCE);
         }
         else if(strcmp(attr, "src") == 0)
         {
            src_curie = value;
            src = rdfa_resolve_curie(context, src_curie, CURIE_PARSE_HREF_SRC);
         }
         else if(strcmp(attr, "typeof") == 0)
         {
            type_of_curie = value;
            type_of = rdfa_resolve_curie_list(
               context, type_of_curie,
               CURIE_PARSE_INSTANCEOF_DATATYPE);
         }
         else if(strcmp(attr, "rel") == 0)
         {
            context->rel_present = 1;
            rel_curie = value;
            rel = rdfa_resolve_curie_list(
               context, rel_curie, CURIE_PARSE_RELREV);
         }
         else if(strcmp(attr, "rev") == 0)
         {
            context->rev_present = 1;
            rev_curie = value;
            rev = rdfa_resolve_curie_list(
               context, rev_curie, CURIE_PARSE_RELREV);
         }
         else if(strcmp(attr, "property") == 0)
         {
            property_curie = value;
            property =
               rdfa_resolve_curie_list(
                  context, property_curie, CURIE_PARSE_PROPERTY);
         }
         else if(strcmp(attr, "resource") == 0)
         {
            resource_curie = value;
            resource = rdfa_resolve_curie(
               context, resource_curie, CURIE_PARSE_ABOUT_RESOURCE);
         }
         else if(strcmp(attr, "href") == 0)
         {
            href_curie = value;
            href =
               rdfa_resolve_curie(context, href_curie, CURIE_PARSE_HREF_SRC);
         }
         else if(strcmp(attr, "content") == 0)
         {
            content = rdfa_replace_string(content, value);
         }
         else if(strcmp(attr, "datatype") == 0)
         {
            datatype_curie = value;

            if(strlen(datatype_curie) == 0)
            {
               datatype = rdfa_replace_string(datatype, "");
            }
            else
            {
               datatype = rdfa_resolve_curie(context, datatype_curie,
                  CURIE_PARSE_INSTANCEOF_DATATYPE);
            }
         }
         else if((attrns == NULL && strcmp(attr, "lang") == 0) ||
            (attrns != NULL && strcmp(attrns, "xml") == 0 &&
               strcmp(attr, "lang") == 0))
         {
            xml_lang = rdfa_replace_string(xml_lang, value);
         }

         free(value);
      }
   }

   /* The root element has an implicit @about declaration */
   if(context->depth == 1 && about == NULL && resource == NULL &&
      href == NULL && src == NULL)
   {
      about_curie = "";
      about = rdfa_resolve_curie(
         context, about_curie, CURIE_PARSE_ABOUT_RESOURCE);
   }

   /* The HEAD and BODY element in XHTML and HTML has an implicit
    * about="" on it.
    */
   if(about == NULL && resource == NULL && href == NULL && src == NULL &&
      (context->parent_subject == NULL || type_of != NULL) &&
      ((context->host_language == HOST_LANGUAGE_XHTML1 ||
      context->host_language == HOST_LANGUAGE_HTML) &&
      (strcasecmp(name, "head") == 0 || strcasecmp(name, "body") == 0)))
   {
      about_curie = "";
      about = rdfa_resolve_curie(
         context, about_curie, CURIE_PARSE_ABOUT_RESOURCE);
   }

   /* check to see if we should append an xml:lang to the XML Literal
    * if one is defined in the context and does not exist on the
    * element. */
   if((xml_lang == NULL) && (context->language != NULL) &&
      !context->xml_literal_xml_lang_defined)
   {
      context->xml_literal = rdfa_n_append_string(
         context->xml_literal, &context->xml_literal_size,
         " xml:lang=\"", strlen(" xml:lang=\""));
      context->xml_literal = rdfa_n_append_string(
         context->xml_literal, &context->xml_literal_size,
         context->language, strlen(context->language));
      context->xml_literal = rdfa_n_append_string(
         context->xml_literal, &context->xml_literal_size, "\"", 1);

      /* ensure that the lang isn't set in a subtree (unless it's overwritten) */
      context->xml_literal_xml_lang_defined = 1;
   }

   /* close the XML Literal value */
   context->xml_literal = rdfa_n_append_string(
      context->xml_literal, &context->xml_literal_size, ">", 1);

   /* 3. The [current element] is also parsed for any language
    *    information, and [language] is set in the [current
    *    evaluation context]; */
   rdfa_update_language(context, xml_lang);

   /***************** FOR DEBUGGING PURPOSES ONLY ******************/
#if defined(DEBUG) && DEBUG > 0
      printf("DEBUG: depth = %u\n", context->depth);
      if(about != NULL)
      {
         printf("DEBUG: @about = %s\n", about);
      }
      if(src != NULL)
      {
         printf("DEBUG: @src = %s\n", src);
      }
      if(type_of != NULL)
      {
         printf("DEBUG: @type_of = ");
         rdfa_print_list(type_of);
      }
      if(context->inlist_present)
      {
         printf("DEBUG: @inlist = true\n");
      }
      if(rel != NULL)
      {
         printf("DEBUG: @rel = ");
         rdfa_print_list(rel);
      }
      if(rev != NULL)
      {
         printf("DEBUG: @rev = ");
         rdfa_print_list(rev);
      }
      if(property != NULL)
      {
         printf("DEBUG: @property = ");
         rdfa_print_list(property);
      }
      if(resource != NULL)
      {
         printf("DEBUG: @resource = %s\n", resource);
      }
      if(href != NULL)
      {
         printf("DEBUG: @href = %s\n", href);
      }
      if(content != NULL)
      {
         printf("DEBUG: @content = %s\n", content);
      }
      if(datatype != NULL)
      {
         printf("DEBUG: @datatype = %s\n", datatype);
      }
      if(xml_lang != NULL)
      {
         printf("DEBUG: @xml:lang = %s\n", xml_lang);
      }
#endif

   /* TODO: This isn't part of the processing model, it needs to be
    * included and is a correction for the last item in step #4. */
   if((about == NULL) && (src == NULL) && (type_of == NULL) &&
      (rel == NULL) && (rev == NULL) && (property == NULL) &&
      (resource == NULL) && (href == NULL) &&
      (context->default_vocabulary == NULL) && (prefix == NULL))
   {
      context->skip_element = 1;
   }

   if((rel == NULL) && (rev == NULL))
   {
      if(context->rdfa_version == RDFA_VERSION_1_0)
      {
         /* 4. If the [current element] contains no valid @rel or @rev
          * URI, obtained according to the section on CURIE and URI
          * Processing, then the next step is to establish a value for
          * [new subject]. Any of the attributes that can carry a
          * resource can set [new subject]; */
         rdfa_establish_new_1_0_subject(
            context, name, about, src, resource, href, type_of);
      }
      else
      {
         rdfa_establish_new_1_1_subject(
            context, name, about, src, resource, href, type_of, property,
            content, datatype);
      }
   }
   else
   {
      if(context->rdfa_version == RDFA_VERSION_1_0)
      {
         /* 5. If the [current element] does contain a valid @rel or @rev
          * URI, obtained according to the section on CURIE and URI
          * Processing, then the next step is to establish both a value
          * for [new subject] and a value for [current object resource]: */
         rdfa_establish_new_1_0_subject_with_relrev(
            context, name, about, src, resource, href, type_of);
      }
      else
      {
         rdfa_establish_new_1_1_subject_with_relrev(
            context, name, about, src, resource, href, type_of);
      }
   }

   if(context->new_subject != NULL)
   {
#if defined(DEBUG) && DEBUG > 0
     printf("DEBUG: new_subject = %s\n", context->new_subject);
#endif

      /* RDFa 1.0: 6. If in any of the previous steps a [new subject] was set
       * to a non-null value, it is now used to provide a subject for
       * type values; */
      /* RDFa 1.1: 7. If in any of the previous steps a typed resource was set
       * to a non-null value, it is now used to provide a subject for type
       * values;
       */
      if(type_of != NULL)
      {
         rdfa_complete_type_triples(context, type_of);
      }

      /* Note that none of this block is executed if there is no
       * [new subject] value, i.e., [new subject] remains null. */
   }

   if(context->current_object_resource != NULL)
   {
      /* If the element contains both the @inlist and the @rel attributes:
       * the @rel may contain one or more resources, obtained according to
       * the section on CURIE and IRI Processing each of which is used to
       * add an entry to the list mapping as follows:
       * if the local list mapping does not contain a list associated with
       * the IRI, instantiate a new list and add to local list mappings
       * add the current object resource to the list associated with the
       * resource in the local list mapping */
      if(context->rdfa_version == RDFA_VERSION_1_1 && (rel != NULL) &&
         context->inlist_present)
      {
         rdfresource_t object_type = RDF_TYPE_IRI;
         if((property != NULL) || (content != NULL))
         {
            object_type = RDF_TYPE_PLAIN_LITERAL;
            if(datatype != NULL)
            {
               object_type = RDF_TYPE_TYPED_LITERAL;
            }
         }
         rdfa_establish_new_inlist_triples(
            context, rel, context->current_object_resource, object_type);
      }

      /* 7. If in any of the previous steps a [current object  resource]
       * was set to a non-null value, it is now used to generate triples */
      rdfa_complete_relrev_triples(context, rel, rev);
   }

   if((context->current_object_resource == NULL) &&
      context->rdfa_version == RDFA_VERSION_1_1  && (rel != NULL) &&
      context->inlist_present)
   {
      rdfa_save_incomplete_list_triples(context, rel);
   }
   else if((context->current_object_resource == NULL) &&
      ((rel != NULL) || (rev != NULL)))
   {
      /* 8. If however [current object resource] was set to null, but
       * there are predicates present, then they must be stored as
       * [incomplete triple]s, pending the discovery of a subject that
       * can be used as the object. Also, [current object resource]
       * should be set to a newly created [bnode] */
      rdfa_save_incomplete_triples(context, rel, rev);
   }

   /* Ensure to re-insert XML Literal namespace information from this
    * point on... */
   if(property != NULL)
   {
      context->xml_literal_namespaces_defined = 0;
   }

   /* save these for processing steps #9 and #10 */
   context->about = rdfa_replace_string(context->about, about);
   context->resource = rdfa_replace_string(context->resource, resource);
   context->href = rdfa_replace_string(context->href, href);
   context->src = rdfa_replace_string(context->src, src);
   context->content = rdfa_replace_string(context->content, content);
   context->datatype = rdfa_replace_string(context->datatype, datatype);
   context->property = property;

   /* free the resolved CURIEs */
   free(about);
   free(src);
   rdfa_free_list(type_of);
   rdfa_free_list(rel);
   rdfa_free_list(rev);
   free(xml_lang);
   free(content);
   free(resource);
   free(href);
   free(datatype);
}
Example #20
0
/**
 * librdf_new_sql_config:
 * @world: librdf_world
 * @storage_name: SQL storage name
 * @layout: SQL schema variant
 * @config_dir: directory for configuration files
 * @predicate_uri_strings: configuration predicate URIs to look for
 * 
 * Constructor - Make a new SQL configuration for a layout from a file
 *
 * Uses SQL storage name @storage_name and with database schema
 * @layout to give a configuration that will contain an array of
 * string values in the #librdf_sql_config field values array.
 * 
 * Return value: configuration or NULL on failure
 **/
librdf_sql_config*
librdf_new_sql_config(librdf_world* world,
                      const char* storage_name,
                      const char* layout,
                      const char* config_dir,
                      const char** predicate_uri_strings)
{
  raptor_parser* rdf_parser=NULL;
  unsigned char *uri_string=NULL;
  raptor_uri *base_uri;
  raptor_uri *uri;
  librdf_sql_config* config;
  size_t len;
  int i;
  
  librdf_world_open(world);

  config=(librdf_sql_config*)LIBRDF_MALLOC(librdf_sql_config,
                                           sizeof(librdf_sql_config));

  len=strlen(config_dir) + 1 + strlen(storage_name) + 4 + 1;
  if(layout)
    len+= strlen(layout) + 1;
  config->filename=(char*)LIBRDF_MALLOC(cstring, len);
  if(layout)
    sprintf(config->filename, "%s/%s-%s.ttl", config_dir, storage_name, layout);
  else
    sprintf(config->filename, "%s/%s.ttl", config_dir, storage_name);

  config->predicate_uri_strings=predicate_uri_strings;
  for(i=0; config->predicate_uri_strings[i]; i++)
    ;
  config->predicates_count=i;
  config->values=(char**)LIBRDF_CALLOC(cstring, sizeof(char*), 
                                       config->predicates_count);
  
  LIBRDF_DEBUG4("Attempting to open %s layout %s storage config file %s\n", 
                storage_name, (layout ? layout: "(default)"), config->filename);
  
  if(access((const char*)config->filename, R_OK)) {
    librdf_log(world, 0, LIBRDF_LOG_ERROR, LIBRDF_FROM_STORAGE, NULL,
               "Failed to open configuration file %s for storage %s layout %s - %s",
               config->filename, storage_name, (layout ? layout: "(default)"),
               strerror(errno));
    librdf_free_sql_config(config);
    return NULL;
  }
  
  uri_string=raptor_uri_filename_to_uri_string(config->filename);
  uri=raptor_new_uri(uri_string);
  base_uri=raptor_uri_copy(uri);
  
  rdf_parser=raptor_new_parser("turtle");
  raptor_set_statement_handler(rdf_parser, config,
                               librdf_sql_config_store_triple);
  raptor_parse_file(rdf_parser, uri, base_uri);
  raptor_free_parser(rdf_parser);
  
  raptor_free_uri(base_uri);
  raptor_free_memory(uri_string);
  raptor_free_uri(uri);

  /* Check all values are given */
  for(i=0; i < config->predicates_count; i++) {
    if(!config->values[i]) {
      librdf_log(world, 0, LIBRDF_LOG_ERROR, LIBRDF_FROM_STORAGE, NULL,
                 "Configuration %s missing for storage %s",
                 config->predicate_uri_strings[i], storage_name);
      librdf_free_sql_config(config);
      return NULL;
    }
  }
  
  return config;
}
/*
 * rasqal_query_results_write_sparql_xml:
 * @iostr: #raptor_iostream to write the query results to
 * @results: #rasqal_query_results query results input
 * @base_uri: #raptor_uri base URI of the output format
 *
 * Write the fourth version of the SPARQL XML query results format to an
 * iostream in a format - INTERNAL.
 * 
 * If the writing succeeds, the query results will be exhausted.
 * 
 * Return value: non-0 on failure
 **/
static int
rasqal_query_results_write_sparql_xml(rasqal_query_results_formatter* formatter,
                                      raptor_iostream *iostr,
                                      rasqal_query_results* results,
                                      raptor_uri *base_uri)
{
  int rc=1;
  rasqal_world* world = rasqal_query_results_get_world(results);
  raptor_xml_writer* xml_writer=NULL;
  raptor_namespace *res_ns=NULL;
  raptor_namespace_stack *nstack=NULL;
  raptor_xml_element *sparql_element=NULL;
  raptor_xml_element *results_element=NULL;
  raptor_xml_element *result_element=NULL;
  raptor_xml_element *element1=NULL;
  raptor_xml_element *binding_element=NULL;
  raptor_xml_element *variable_element=NULL;
  raptor_qname **attrs=NULL;
  int i;
  rasqal_query_results_type type;

  type = rasqal_query_results_get_type(results);

  if(type != RASQAL_QUERY_RESULTS_BINDINGS &&
     type != RASQAL_QUERY_RESULTS_BOOLEAN) {
    rasqal_log_error_simple(world, RAPTOR_LOG_LEVEL_ERROR,
                            NULL,
                            "Cannot write XML format v3 for %s query result format",
                            rasqal_query_results_type_label(type));
    return 1;
  }

  nstack = raptor_new_namespaces(world->raptor_world_ptr, 1);
  if(!nstack)
    return 1;

  xml_writer = raptor_new_xml_writer(world->raptor_world_ptr,
                                     nstack,
                                     iostr);
  if(!xml_writer)
    goto tidy;

  res_ns=raptor_new_namespace(nstack,
                              NULL,
                              RASQAL_GOOD_CAST(const unsigned char*, "http://www.w3.org/2005/sparql-results#"),
                              0);
  if(!res_ns)
    goto tidy;

  sparql_element=raptor_new_xml_element_from_namespace_local_name(res_ns,
                                                                  RASQAL_GOOD_CAST(const unsigned char*, "sparql"),
                                                                  NULL, base_uri);
  if(!sparql_element)
    goto tidy;

  raptor_xml_writer_start_element(xml_writer, sparql_element);
  raptor_xml_writer_raw_counted(xml_writer, RASQAL_GOOD_CAST(const unsigned char*, "\n"), 1);

  /*   <head> */
  element1=raptor_new_xml_element_from_namespace_local_name(res_ns,
                                                            RASQAL_GOOD_CAST(const unsigned char*, "head"),
                                                            NULL, base_uri);
  if(!element1)
    goto tidy;

  raptor_xml_writer_raw_counted(xml_writer, RASQAL_GOOD_CAST(const unsigned char*, "  "), 2);
  raptor_xml_writer_start_element(xml_writer, element1);
  raptor_xml_writer_raw_counted(xml_writer, RASQAL_GOOD_CAST(const unsigned char*, "\n"), 1);
  
  if(rasqal_query_results_is_bindings(results)) {
    for(i=0; 1; i++) {
      const unsigned char *name;
      name=rasqal_query_results_get_binding_name(results, i);
      if(!name)
        break;
      
      /*     <variable name="x"/> */
      variable_element=raptor_new_xml_element_from_namespace_local_name(res_ns,
                                                                        RASQAL_GOOD_CAST(const unsigned char*,"variable"),
                                                                        NULL, base_uri);
      if(!variable_element)
        goto tidy;
      
      attrs=(raptor_qname **)raptor_alloc_memory(sizeof(raptor_qname*));
      if(!attrs)
        goto tidy;
      attrs[0] = raptor_new_qname_from_namespace_local_name(world->raptor_world_ptr,
                                                            res_ns,
                                                            RASQAL_GOOD_CAST(const unsigned char*,"name"),
                                                            RASQAL_GOOD_CAST(const unsigned char*, name)); /* attribute value */
      if(!attrs[0]) {
        raptor_free_memory((void*)attrs);
        goto tidy;
      }

      raptor_xml_element_set_attributes(variable_element, attrs, 1);
      
      raptor_xml_writer_raw_counted(xml_writer, RASQAL_GOOD_CAST(const unsigned char*, "    "), 4);
      raptor_xml_writer_empty_element(xml_writer, variable_element);
      raptor_xml_writer_raw_counted(xml_writer, RASQAL_GOOD_CAST(const unsigned char*, "\n"), 1);
      
      raptor_free_xml_element(variable_element);
      variable_element=NULL;
    }
  }

  /* FIXME - could add <link> inside <head> */

    
  /*   </head> */
  raptor_xml_writer_raw_counted(xml_writer, RASQAL_GOOD_CAST(const unsigned char*, "  "), 2);
  raptor_xml_writer_end_element(xml_writer, element1);
  raptor_xml_writer_raw_counted(xml_writer, RASQAL_GOOD_CAST(const unsigned char*, "\n"), 1);
  
  raptor_free_xml_element(element1);
  element1=NULL;


  /* Boolean Results */
  if(rasqal_query_results_is_boolean(results)) {
    result_element=raptor_new_xml_element_from_namespace_local_name(res_ns,
                                                                    RASQAL_GOOD_CAST(const unsigned char*, "boolean"),
                                                                    NULL, base_uri);
    if(!result_element)
      goto tidy;

    raptor_xml_writer_raw_counted(xml_writer, RASQAL_GOOD_CAST(const unsigned char*, "  "), 2);
    raptor_xml_writer_start_element(xml_writer, result_element);
    if(rasqal_query_results_get_boolean(results))
      raptor_xml_writer_raw(xml_writer, RASQAL_XSD_BOOLEAN_TRUE);
    else
      raptor_xml_writer_raw(xml_writer, RASQAL_XSD_BOOLEAN_FALSE);
    raptor_xml_writer_end_element(xml_writer, result_element);
    raptor_xml_writer_raw_counted(xml_writer, RASQAL_GOOD_CAST(const unsigned char*, "\n"), 1);

    goto results3done;
  }


  /* Variable Binding Results */

  /*   <results> */
  results_element=raptor_new_xml_element_from_namespace_local_name(res_ns,
                                                                   RASQAL_GOOD_CAST(const unsigned char*, "results"),
                                                                   NULL, base_uri);
  if(!results_element)
    goto tidy;

  raptor_xml_writer_raw_counted(xml_writer, RASQAL_GOOD_CAST(const unsigned char*, "  "), 2);
  raptor_xml_writer_start_element(xml_writer, results_element);
  raptor_xml_writer_raw_counted(xml_writer, RASQAL_GOOD_CAST(const unsigned char*, "\n"), 1);


  /* declare result element for later multiple use */
  result_element=raptor_new_xml_element_from_namespace_local_name(res_ns,
                                                                  RASQAL_GOOD_CAST(const unsigned char*, "result"),
                                                                  NULL, base_uri);
  if(!result_element)
    goto tidy;

  while(!rasqal_query_results_finished(results)) {
    /*     <result> */
    raptor_xml_writer_raw_counted(xml_writer, RASQAL_GOOD_CAST(const unsigned char*, "    "), 4);
    raptor_xml_writer_start_element(xml_writer, result_element);
    raptor_xml_writer_raw_counted(xml_writer, RASQAL_GOOD_CAST(const unsigned char*, "\n"), 1);

    for(i=0; i<rasqal_query_results_get_bindings_count(results); i++) {
      const unsigned char *name=rasqal_query_results_get_binding_name(results, i);
      rasqal_literal *l=rasqal_query_results_get_binding_value(results, i);

      /*       <binding> */
      binding_element=raptor_new_xml_element_from_namespace_local_name(res_ns,
                                                                       RASQAL_GOOD_CAST(const unsigned char*, "binding"),
                                                                       NULL, base_uri);
      if(!binding_element)
        goto tidy;

      attrs=(raptor_qname **)raptor_alloc_memory(sizeof(raptor_qname*));
      if(!attrs)
        goto tidy;
      attrs[0] = raptor_new_qname_from_namespace_local_name(world->raptor_world_ptr,
                                                            res_ns,
                                                            RASQAL_GOOD_CAST(const unsigned char*, "name"),
                                                            name);

      if(!attrs[0]) {
        raptor_free_memory((void*)attrs);
        goto tidy;
      }

      raptor_xml_element_set_attributes(binding_element, attrs, 1);
      

      raptor_xml_writer_raw_counted(xml_writer, RASQAL_GOOD_CAST(const unsigned char*, "      "), 6);
      raptor_xml_writer_start_element(xml_writer, binding_element);

      if(!l) {
        element1=raptor_new_xml_element_from_namespace_local_name(res_ns,
                                                                  RASQAL_GOOD_CAST(const unsigned char*, "unbound"),
                                                                  NULL, base_uri);
        if(!element1)
          goto tidy;
        raptor_xml_writer_empty_element(xml_writer, element1);

      } else switch(l->type) {
        case RASQAL_LITERAL_URI:
          element1=raptor_new_xml_element_from_namespace_local_name(res_ns,
                                                                    RASQAL_GOOD_CAST(const unsigned char*, "uri"),
                                                                    NULL, base_uri);
          if(!element1)
            goto tidy;
          
          raptor_xml_writer_start_element(xml_writer, element1);
          raptor_xml_writer_cdata(xml_writer, RASQAL_GOOD_CAST(const unsigned char*, raptor_uri_as_string(l->value.uri)));
          raptor_xml_writer_end_element(xml_writer, element1);

          break;

        case RASQAL_LITERAL_BLANK:
          element1=raptor_new_xml_element_from_namespace_local_name(res_ns,
                                                                    RASQAL_GOOD_CAST(const unsigned char*, "bnode"),
                                                                    NULL, base_uri);
          if(!element1)
            goto tidy;
          
          raptor_xml_writer_start_element(xml_writer, element1);
          raptor_xml_writer_cdata(xml_writer, RASQAL_GOOD_CAST(const unsigned char*, l->string));
          raptor_xml_writer_end_element(xml_writer, element1);
          break;

        case RASQAL_LITERAL_STRING:
        case RASQAL_LITERAL_UDT:
          element1=raptor_new_xml_element_from_namespace_local_name(res_ns,
                                                                    RASQAL_GOOD_CAST(const unsigned char*, "literal"),
                                                                    NULL, base_uri);
          if(!element1)
            goto tidy;

          if(l->language || l->datatype) {
            attrs=(raptor_qname **)raptor_alloc_memory(sizeof(raptor_qname*));
            if(!attrs)
              goto tidy;

            if(l->language)
              attrs[0]=raptor_new_qname(nstack,
                                        RASQAL_GOOD_CAST(const unsigned char*, "xml:lang"),
                                        RASQAL_GOOD_CAST(const unsigned char*, l->language));
            else
              attrs[0] = raptor_new_qname_from_namespace_local_name(world->raptor_world_ptr,
                                                                    res_ns,
                                                                    RASQAL_GOOD_CAST(const unsigned char*, "datatype"),
                                                                    RASQAL_GOOD_CAST(const unsigned char*, raptor_uri_as_string(l->datatype)));
            if(!attrs[0]) {
              raptor_free_memory((void*)attrs);
              goto tidy;
            }

            raptor_xml_element_set_attributes(element1, attrs, 1);
          }
Example #22
0
int
main(int argc, char *argv[]) 
{ 
  rasqal_world *world;
  raptor_world* raptor_world_ptr = NULL;
  int rc = 0;
  int usage = 0;
  int help = 0;
  const char* query_language = DEFAULT_QUERY_LANGUAGE;
  const char* query_filename = NULL;
  const char* data_format_name = NULL;
  const char* result_filename = NULL;
  const char* result_format_name = NULL;
  unsigned char* query_string = NULL;
  size_t query_len = 0;
  unsigned char *query_base_uri_string = NULL;
  int free_query_base_uri_string = 0;
  raptor_uri* query_base_uri = NULL;
  rasqal_query* rq = NULL;
  rasqal_query_results* results = NULL;
  rasqal_query_results* expected_results = NULL;
  raptor_sequence* data_graphs = NULL;
  raptor_iostream* result_iostr = NULL;
  rasqal_dataset* ds = NULL;
  rasqal_query_results_type results_type;

  /* Set globals */
  if(1) {
    char *p;
    
    program = argv[0];
    if((p = strrchr(program, '/')))
      program = p + 1;
    else if((p = strrchr(program, '\\')))
      program = p + 1;
    argv[0] = program;
  }
  
  world = rasqal_new_world();
  if(!world || rasqal_world_open(world)) {
    fprintf(stderr, "%s: rasqal_world init failed\n", program);
    return(1);
  }
  
  raptor_world_ptr = rasqal_world_get_raptor(world);
  rasqal_world_set_log_handler(world, world, check_query_log_handler);

  /* Option parsing */
  while (!usage && !help)
  {
    int c;
    
#ifdef HAVE_GETOPT_LONG
    int option_index = 0;

    c = getopt_long (argc, argv, GETOPT_STRING, long_options, &option_index);
#else
    c = getopt (argc, argv, GETOPT_STRING);
#endif
    if (c == -1)
      break;

    switch (c) {
      case 0:
      case '?': /* getopt() - unknown option */
        usage = 1;
        break;
        
      case 'd':
        verbose++;
        break;

      case 'F':
        if(optarg) {
          data_format_name = optarg;
        }
        break;
        
      case 'h':
        help = 1;
        break;

      case 'l':
        if(optarg) {
          query_language = optarg;
        }
        break;

      case 'q':
        if(optarg) {
          query_filename = optarg;
        }
        break;

      case 'Q':
        if(optarg) {
          query_base_uri_string = (unsigned char*)optarg;
        }
        break;

      case 'r':
        if(optarg) {
          result_filename = optarg;
        }
        break;
        
      case 'R':
        if(optarg) {
          result_format_name = optarg;
        }
        break;
        
      case 'v':
        fputs(rasqal_version_string, stdout);
        fputc('\n', stdout);
        rasqal_free_world(world);
        exit(0);

      case 'g':
      case 'n':
        if(optarg) {
          rasqal_data_graph *dg = NULL;
          rasqal_data_graph_flags type;

          type = (c == 'n') ? RASQAL_DATA_GRAPH_NAMED : 
                              RASQAL_DATA_GRAPH_BACKGROUND;

          if(!access((const char*)optarg, R_OK)) {
            /* file: use URI */
            unsigned char* source_uri_string;
            raptor_uri* source_uri;
            raptor_uri* graph_name = NULL;

            source_uri_string = raptor_uri_filename_to_uri_string((const char*)optarg);
            source_uri = raptor_new_uri(raptor_world_ptr, source_uri_string);
            raptor_free_memory(source_uri_string);

            if(type == RASQAL_DATA_GRAPH_NAMED) 
              graph_name = source_uri;
            
            if(source_uri)
              dg = rasqal_new_data_graph_from_uri(world,
                                                  source_uri,
                                                  graph_name,
                                                  type,
                                                  NULL, data_format_name,
                                                  NULL);

            if(source_uri)
              raptor_free_uri(source_uri);
          } else {
            raptor_uri* source_uri;
            raptor_uri* graph_name = NULL;

            /* URI: use URI */
            source_uri = raptor_new_uri(raptor_world_ptr,
                                        (const unsigned char*)optarg);
            if(type == RASQAL_DATA_GRAPH_NAMED) 
              graph_name = source_uri;
            
            if(source_uri)
              dg = rasqal_new_data_graph_from_uri(world,
                                                  source_uri,
                                                  graph_name,
                                                  type,
                                                  NULL, data_format_name,
                                                  NULL);

            if(source_uri)
              raptor_free_uri(source_uri);
          }
          
          if(!dg) {
            fprintf(stderr, "%s: Failed to create data graph for `%s'\n",
                    program, optarg);
            return(1);
          }
          
          if(!data_graphs) {
            data_graphs = raptor_new_sequence((raptor_data_free_handler)rasqal_free_data_graph,
                                              NULL);

            if(!data_graphs) {
              fprintf(stderr, "%s: Failed to create data graphs sequence\n",
                      program);
              return(1);
            }
          }

          raptor_sequence_push(data_graphs, dg);
        }
        break;

    }
    
  } /* end while option */


  if(!help && !usage) {
    if(optind != argc) {
      fprintf(stderr, "%s: Extra arguments.\n", program);
      usage = 1;
    } else if(!result_filename) {
      usage = 2; /* Title and usage */
    } else if(!query_filename) {
      usage = 2; /* Title and usage */
    }
  }

  
  if(usage) {
    if(usage > 1) {
      fprintf(stderr, title_format_string, rasqal_version_string);
      fputs("Rasqal home page: ", stderr);
      fputs(rasqal_home_url_string, stderr);
      fputc('\n', stderr);
      fputs(rasqal_copyright_string, stderr);
      fputs("\nLicense: ", stderr);
      fputs(rasqal_license_string, stderr);
      fputs("\n\n", stderr);
    }
    fprintf(stderr, "Try `%s " HELP_ARG(h, help) "' for more information.\n",
            program);
    rasqal_free_world(world);

    exit(1);
  }

  if(help) {
    int i;

    printf(title_format_string, rasqal_version_string);
    puts("Run an RDF query and check it against a known result.");
    printf("Usage: %s [OPTIONS] -g DATA -q QUERY-FILE -r RESULT-FILE\n\n", program);

    fputs(rasqal_copyright_string, stdout);
    fputs("\nLicense: ", stdout);
    puts(rasqal_license_string);
    fputs("Rasqal home page: ", stdout);
    puts(rasqal_home_url_string);

    puts("\nNormal operation is to execute the query in the QUERY-FILE and\ncompare to the query results in RESULT-FILE.");
    puts("\nMain options:");
    puts(HELP_TEXT("g URI", "default-graph URI", "Use URI as the default graph in the dataset"));
    puts(HELP_TEXT("l", "language LANGUAGE    ", "Set query language name to one of:"));
    for(i = 0; 1; i++) {
      const raptor_syntax_description* desc;

      desc = rasqal_world_get_query_language_description(world, i);
      if(!desc)
         break;

      printf("    %-15s              %s", desc->names[0], desc->label);
      if(!i)
        puts(" (default)");
      else
        putchar('\n');
    }
    puts(HELP_TEXT("n URI", "named-graph URI  ", "Add named graph URI to dataset"));
    puts(HELP_TEXT("q FILE", "query QUERY-FILE", "Execute query in file QUERY-FILE"));
    puts(HELP_TEXT("r FILE", "result FILE     ", "Compare to result in file RESULTS-FILE"));


    puts("\nAdditional options:");
    puts(HELP_TEXT("d", "debug                ", "Increase debug message level"));
    puts(HELP_TEXT("F", "data-format NAME     ", "Set the data source format NAME (default: " DEFAULT_DATA_FORMAT_NAME_GRAPH ")"));
    puts(HELP_TEXT("h", "help                 ", "Print this help, then exit"));
    puts(HELP_TEXT("Q URI", "query-base-uri URI", "Set the base URI for the query"));
    puts(HELP_TEXT("R", "result-format NAME   ", "Set the result format NAME (default: " DEFAULT_RESULT_FORMAT_NAME_GRAPH ")"));
    puts("    For variable bindings and boolean results:");

    for(i = 0; 1; i++) {
      const raptor_syntax_description* desc;
 
      desc = rasqal_world_get_query_results_format_description(world, i);
      if(!desc)
         break;
 
      if(desc->flags & RASQAL_QUERY_RESULTS_FORMAT_FLAG_READER) {
        printf("      %-10s     %s", desc->names[0], desc->label);
        if(!strcmp(desc->names[0], DEFAULT_RESULT_FORMAT_NAME_GRAPH))
          puts(" (default)");
        else
          putchar('\n');
      }
    }

    puts("    For RDF graph results:");

    for(i = 0; 1; i++) {
      const raptor_syntax_description *desc;
      desc = raptor_world_get_parser_description(raptor_world_ptr, i);
      if(!desc)
        break;

      printf("      %-15s%s", desc->names[0], desc->label);
      if(!strcmp(desc->names[0], DEFAULT_DATA_FORMAT_NAME_GRAPH))
        puts(" (default)");
      else
        putchar('\n');
    }
    puts(HELP_TEXT("v", "version              ", "Print the Rasqal version"));

    puts("\nReport bugs to http://bugs.librdf.org/");

    rasqal_free_world(world);
    
    exit(0);
  }


  /* Compute query base URI from filename or passed in -Q QUERY-BASE-URI */
  if(!query_base_uri_string) {
    query_base_uri_string = raptor_uri_filename_to_uri_string(query_filename);
    free_query_base_uri_string = 1;
  }
  
  query_base_uri = raptor_new_uri(raptor_world_ptr, query_base_uri_string);
  if(!query_base_uri) {
    fprintf(stderr, "%s: Failed to create URI for %s\n",
            program, query_base_uri_string);
    return(1);
  }

  /* Read query from file into a string */
  query_string = check_query_read_file_string(query_filename,
                                              "query file", &query_len);
  if(!query_string) {
    rc = 1;
    goto tidy_setup;
  }


  /* Report information */
  if(verbose) {
    fprintf(stderr, "%s: Reading query in language %s from file %s  URI %s:\n", 
            program, query_language, query_filename,
            raptor_uri_as_string(query_base_uri));
    if(verbose > 1)
      fprintf(stderr, "%s\n", (const char*)query_string);
    fprintf(stderr, "%s: Reading results from file '%s'\n", 
            program, result_filename);
  }


  /* Parse and prepare query */
  rq = check_query_init_query(world, query_language, query_string,
                              query_base_uri, data_graphs);
  if(!rq) {
    fprintf(stderr, "%s: Parsing query in %s failed\n", program,
            query_filename);
    goto tidy_query;
  }

  /* Query prepared OK - we now know the query details such as result type */


  /* Read expected results */
  if(1) {
    results_type = rasqal_query_get_result_type(rq);
    fprintf(stderr, "%s: Expecting result type %d\n", program, results_type);

    /* Read result file */
    result_iostr = raptor_new_iostream_from_filename(raptor_world_ptr,
                                                     result_filename);
    if(!result_iostr) {
      fprintf(stderr, "%s: result file '%s' open failed - %s", 
              program, result_filename, strerror(errno));
      rc = 1;
      goto tidy_setup;
    }


    switch(results_type) {
      case RASQAL_QUERY_RESULTS_BINDINGS:
      case RASQAL_QUERY_RESULTS_BOOLEAN:
        /* read results via rasqal query results format */
        expected_results = check_query_read_results(world,
                                                    raptor_world_ptr,
                                                    results_type,
                                                    result_iostr,
                                                    result_filename,
                                                    result_format_name);
        raptor_free_iostream(result_iostr); result_iostr = NULL;

        break;

      case RASQAL_QUERY_RESULTS_GRAPH:
        /* read results via raptor parser */

        if(1) {
          const char* format_name = NULL;

          if(result_format_name) {
            if(!raptor_world_is_parser_name(raptor_world_ptr,
                                            result_format_name)) {
              fprintf(stderr,
                      "%s: invalid parser name `%s' for `" HELP_ARG(R, result-format) "'\n\n",
                      program, result_format_name);
            } else
              format_name = result_format_name;
          }

          if(!format_name)
            format_name = DEFAULT_RESULT_FORMAT_NAME_GRAPH;

          
          ds = rasqal_new_dataset(world);
          if(!ds) {
            fprintf(stderr, "%s: Failed to create dataset", program);
            rc = 1;
            goto tidy_setup;
          }

          if(rasqal_dataset_load_graph_iostream(ds, format_name, 
                                                result_iostr, NULL)) {
            fprintf(stderr, "%s: Failed to load graph into dataset", program);
            rc = 1;
            goto tidy_setup;
          }

          raptor_free_iostream(result_iostr); result_iostr = NULL;

          rasqal_free_dataset(ds); ds = NULL;
        }
        break;
        
      case RASQAL_QUERY_RESULTS_SYNTAX:
        fprintf(stderr, 
                "%s: Reading query results format 'syntax' is not supported", 
                program);
        rc = 1;
        goto tidy_setup;
        break;

      case RASQAL_QUERY_RESULTS_UNKNOWN:
        /* failure */
        fprintf(stderr, "%s: Unknown query result format cannot be tested.", 
                program);
        rc = 1;
        goto tidy_setup;
        break;
    }
    
  }


  /* save results for query execution so we can print and rewind */
  rasqal_query_set_store_results(rq, 1);

  results = rasqal_query_execute(rq);
  if(results) {

    switch(results_type) {
      case RASQAL_QUERY_RESULTS_BINDINGS:
        fprintf(stderr, "%s: Expected bindings results:\n", program);
        print_bindings_result_simple(expected_results, stderr, 1);
        
        fprintf(stderr, "%s: Actual bindings results:\n", program);
        print_bindings_result_simple(results, stderr, 1);

        rasqal_query_results_rewind(expected_results);
        rasqal_query_results_rewind(results);

        /* FIXME: should NOT do this if results are expected to be ordered */
        rasqal_query_results_sort(expected_results, rasqal_row_compare);
        rasqal_query_results_sort(results, rasqal_row_compare);

        if(1) {
          compare_query_results* cqr;
          cqr = new_compare_query_results(world,
                                          expected_results, "expected",
                                          results, "actual");
          compare_query_results_set_log_handler(cqr, world,
                                                check_query_log_handler);
          rc = !compare_query_results_compare(cqr);
          free_compare_query_results(cqr); cqr = NULL;
        }
        
        break;
        
      case RASQAL_QUERY_RESULTS_BOOLEAN:
      case RASQAL_QUERY_RESULTS_GRAPH:
      case RASQAL_QUERY_RESULTS_SYNTAX:
      case RASQAL_QUERY_RESULTS_UNKNOWN:
        /* failure */
        fprintf(stderr, "%s: Query result format %d cannot be tested.", 
                program, results_type);
        rc = 1;
        goto tidy_setup;
        break;
    }
  } else
    rc = 1;


  if(verbose) {
    fprintf(stdout, "%s: Result: %s\n", program, rc ? "FAILURE" : "success");
  }

  if(results) {
    rasqal_free_query_results(results); results = NULL;
  }


  tidy_query:
  if(rq)
    rasqal_free_query(rq);


  tidy_setup:
  if(expected_results)
    rasqal_free_query_results(expected_results);

  if(results)
    rasqal_free_query_results(results);

  if(result_iostr)
    raptor_free_iostream(result_iostr);
  
  if(ds)
    rasqal_free_dataset(ds);

  if(free_query_base_uri_string)
    raptor_free_memory(query_base_uri_string);

  if(query_base_uri)
    raptor_free_uri(query_base_uri);

  if(data_graphs)
    raptor_free_sequence(data_graphs);

  rasqal_free_world(world);
  
  return (rc);
}
Example #23
0
/*
 * rasqal_query_results_write_sparql_xml:
 * @iostr: #raptor_iostream to write the query results to
 * @results: #rasqal_query_results query results input
 * @base_uri: #raptor_uri base URI of the output format
 *
 * Write the fourth version of the SPARQL XML query results format to an
 * iostream in a format - INTERNAL.
 * 
 * If the writing succeeds, the query results will be exhausted.
 * 
 * Return value: non-0 on failure
 **/
static int
rasqal_query_results_write_sparql_xml(rasqal_query_results_formatter* formatter,
                                      raptor_iostream *iostr,
                                      rasqal_query_results* results,
                                      raptor_uri *base_uri)
{
  int rc=1;
  rasqal_world* world = rasqal_query_results_get_world(results);
  raptor_xml_writer* xml_writer=NULL;
  raptor_namespace *res_ns=NULL;
  raptor_namespace_stack *nstack=NULL;
  raptor_xml_element *sparql_element=NULL;
  raptor_xml_element *results_element=NULL;
  raptor_xml_element *result_element=NULL;
  raptor_xml_element *element1=NULL;
  raptor_xml_element *binding_element=NULL;
  raptor_xml_element *variable_element=NULL;
  raptor_qname **attrs=NULL;
  int i;

  if(!rasqal_query_results_is_bindings(results) &&
     !rasqal_query_results_is_boolean(results)) {
    rasqal_log_error_simple(world, RAPTOR_LOG_LEVEL_ERROR,
                            NULL,
                            "Can only write XML format v3 for variable binding and boolean results");
    return 1;
  }
  

  nstack = raptor_new_namespaces(world->raptor_world_ptr, 1);
  if(!nstack)
    return 1;

  xml_writer = raptor_new_xml_writer(world->raptor_world_ptr,
                                     nstack,
                                     iostr);
  if(!xml_writer)
    goto tidy;

  res_ns=raptor_new_namespace(nstack,
                              NULL,
                              (const unsigned char*)"http://www.w3.org/2005/sparql-results#",
                              0);
  if(!res_ns)
    goto tidy;

  sparql_element=raptor_new_xml_element_from_namespace_local_name(res_ns,
                                                                  (const unsigned char*)"sparql",
                                                                  NULL, base_uri);
  if(!sparql_element)
    goto tidy;

  raptor_xml_writer_start_element(xml_writer, sparql_element);
  raptor_xml_writer_raw_counted(xml_writer, (const unsigned char*)"\n", 1);

  /*   <head> */
  element1=raptor_new_xml_element_from_namespace_local_name(res_ns,
                                                            (const unsigned char*)"head",
                                                            NULL, base_uri);
  if(!element1)
    goto tidy;

  raptor_xml_writer_raw_counted(xml_writer, (const unsigned char*)"  ", 2);
  raptor_xml_writer_start_element(xml_writer, element1);
  raptor_xml_writer_raw_counted(xml_writer, (const unsigned char*)"\n", 1);
  
  if(rasqal_query_results_is_bindings(results)) {
    for(i=0; 1; i++) {
      const unsigned char *name;
      name=rasqal_query_results_get_binding_name(results, i);
      if(!name)
        break;
      
      /*     <variable name="x"/> */
      variable_element=raptor_new_xml_element_from_namespace_local_name(res_ns,
                                                                        (const unsigned char*)"variable",
                                                                        NULL, base_uri);
      if(!variable_element)
        goto tidy;
      
      attrs=(raptor_qname **)raptor_alloc_memory(sizeof(raptor_qname*));
      if(!attrs)
        goto tidy;
      attrs[0] = raptor_new_qname_from_namespace_local_name(world->raptor_world_ptr,
                                                            res_ns,
                                                            (const unsigned char*)"name",
                                                            (const unsigned char*)name); /* attribute value */
      if(!attrs[0]) {
        raptor_free_memory((void*)attrs);
        goto tidy;
      }

      raptor_xml_element_set_attributes(variable_element, attrs, 1);
      
      raptor_xml_writer_raw_counted(xml_writer, (const unsigned char*)"    ", 4);
      raptor_xml_writer_empty_element(xml_writer, variable_element);
      raptor_xml_writer_raw_counted(xml_writer, (const unsigned char*)"\n", 1);
      
      raptor_free_xml_element(variable_element);
      variable_element=NULL;
    }
  }

  /* FIXME - could add <link> inside <head> */

    
  /*   </head> */
  raptor_xml_writer_raw_counted(xml_writer, (const unsigned char*)"  ", 2);
  raptor_xml_writer_end_element(xml_writer, element1);
  raptor_xml_writer_raw_counted(xml_writer, (const unsigned char*)"\n", 1);
  
  raptor_free_xml_element(element1);
  element1=NULL;


  /* Boolean Results */
  if(rasqal_query_results_is_boolean(results)) {
    result_element=raptor_new_xml_element_from_namespace_local_name(res_ns,
                                                                    (const unsigned char*)"boolean",
                                                                    NULL, base_uri);
    if(!result_element)
      goto tidy;

    raptor_xml_writer_raw_counted(xml_writer, (const unsigned char*)"  ", 2);
    raptor_xml_writer_start_element(xml_writer, result_element);
    if(rasqal_query_results_get_boolean(results))
      raptor_xml_writer_raw(xml_writer, RASQAL_XSD_BOOLEAN_TRUE);
    else
      raptor_xml_writer_raw(xml_writer, RASQAL_XSD_BOOLEAN_FALSE);
    raptor_xml_writer_end_element(xml_writer, result_element);
    raptor_xml_writer_raw_counted(xml_writer, (const unsigned char*)"\n", 1);

    goto results3done;
  }


  /* Variable Binding Results */

  /*   <results> */
  results_element=raptor_new_xml_element_from_namespace_local_name(res_ns,
                                                                   (const unsigned char*)"results",
                                                                   NULL, base_uri);
  if(!results_element)
    goto tidy;

  raptor_xml_writer_raw_counted(xml_writer, (const unsigned char*)"  ", 2);
  raptor_xml_writer_start_element(xml_writer, results_element);
  raptor_xml_writer_raw_counted(xml_writer, (const unsigned char*)"\n", 1);


  /* declare result element for later multiple use */
  result_element=raptor_new_xml_element_from_namespace_local_name(res_ns,
                                                                  (const unsigned char*)"result",
                                                                  NULL, base_uri);
  if(!result_element)
    goto tidy;

  while(!rasqal_query_results_finished(results)) {
    /*     <result> */
    raptor_xml_writer_raw_counted(xml_writer, (const unsigned char*)"    ", 4);
    raptor_xml_writer_start_element(xml_writer, result_element);
    raptor_xml_writer_raw_counted(xml_writer, (const unsigned char*)"\n", 1);

    for(i=0; i<rasqal_query_results_get_bindings_count(results); i++) {
      const unsigned char *name=rasqal_query_results_get_binding_name(results, i);
      rasqal_literal *l=rasqal_query_results_get_binding_value(results, i);

      /*       <binding> */
      binding_element=raptor_new_xml_element_from_namespace_local_name(res_ns,
                                                                       (const unsigned char*)"binding",
                                                                       NULL, base_uri);
      if(!binding_element)
        goto tidy;

      attrs=(raptor_qname **)raptor_alloc_memory(sizeof(raptor_qname*));
      if(!attrs)
        goto tidy;
      attrs[0] = raptor_new_qname_from_namespace_local_name(world->raptor_world_ptr,
                                                            res_ns,
                                                            (const unsigned char*)"name",
                                                            name);

      if(!attrs[0]) {
        raptor_free_memory((void*)attrs);
        goto tidy;
      }

      raptor_xml_element_set_attributes(binding_element, attrs, 1);
      

      raptor_xml_writer_raw_counted(xml_writer, (const unsigned char*)"      ", 6);
      raptor_xml_writer_start_element(xml_writer, binding_element);

      if(!l) {
        element1=raptor_new_xml_element_from_namespace_local_name(res_ns,
                                                                  (const unsigned char*)"unbound",
                                                                  NULL, base_uri);
        if(!element1)
          goto tidy;
        raptor_xml_writer_empty_element(xml_writer, element1);

      } else switch(l->type) {
        case RASQAL_LITERAL_URI:
          element1=raptor_new_xml_element_from_namespace_local_name(res_ns,
                                                                    (const unsigned char*)"uri",
                                                                    NULL, base_uri);
          if(!element1)
            goto tidy;
          
          raptor_xml_writer_start_element(xml_writer, element1);
          raptor_xml_writer_cdata(xml_writer, (const unsigned char*)raptor_uri_as_string(l->value.uri));
          raptor_xml_writer_end_element(xml_writer, element1);

          break;

        case RASQAL_LITERAL_BLANK:
          element1=raptor_new_xml_element_from_namespace_local_name(res_ns,
                                                                    (const unsigned char*)"bnode",
                                                                    NULL, base_uri);
          if(!element1)
            goto tidy;
          
          raptor_xml_writer_start_element(xml_writer, element1);
          raptor_xml_writer_cdata(xml_writer, (const unsigned char*)l->string);
          raptor_xml_writer_end_element(xml_writer, element1);
          break;

        case RASQAL_LITERAL_STRING:
        case RASQAL_LITERAL_UDT:
          element1=raptor_new_xml_element_from_namespace_local_name(res_ns,
                                                                    (const unsigned char*)"literal",
                                                                    NULL, base_uri);
          if(!element1)
            goto tidy;

          if(l->language || l->datatype) {
            attrs=(raptor_qname **)raptor_alloc_memory(sizeof(raptor_qname*));
            if(!attrs)
              goto tidy;

            if(l->language)
              attrs[0]=raptor_new_qname(nstack,
                                        (const unsigned char*)"xml:lang",
                                        (const unsigned char*)l->language);
            else
              attrs[0] = raptor_new_qname_from_namespace_local_name(world->raptor_world_ptr,
                                                                    res_ns,
                                                                    (const unsigned char*)"datatype",
                                                                    (const unsigned char*)raptor_uri_as_string(l->datatype));
            if(!attrs[0]) {
              raptor_free_memory((void*)attrs);
              goto tidy;
            }

            raptor_xml_element_set_attributes(element1, attrs, 1);
          }


          raptor_xml_writer_start_element(xml_writer, element1);


          raptor_xml_writer_cdata_counted(xml_writer,
                                          (const unsigned char*)l->string, 
                                          l->string_len);

          raptor_xml_writer_end_element(xml_writer, element1);
          
          break;
        case RASQAL_LITERAL_PATTERN:
        case RASQAL_LITERAL_QNAME:
        case RASQAL_LITERAL_INTEGER:
        case RASQAL_LITERAL_XSD_STRING:
        case RASQAL_LITERAL_BOOLEAN:
        case RASQAL_LITERAL_DOUBLE:
        case RASQAL_LITERAL_FLOAT:
        case RASQAL_LITERAL_VARIABLE:
        case RASQAL_LITERAL_DECIMAL:
        case RASQAL_LITERAL_DATETIME:
        case RASQAL_LITERAL_INTEGER_SUBTYPE:

        case RASQAL_LITERAL_UNKNOWN:
        default:
          rasqal_log_error_simple(world, RAPTOR_LOG_LEVEL_ERROR,
                                  NULL,
                                  "Cannot turn literal type %d into XML", 
                                  l->type);
          goto tidy;
        }

      if(element1) {
        raptor_free_xml_element(element1);
        element1=NULL;
      }

      /*       </binding> */
      raptor_xml_writer_end_element(xml_writer, binding_element);
      raptor_xml_writer_raw_counted(xml_writer, (const unsigned char*)"\n", 1);
      
      raptor_free_xml_element(binding_element);
      binding_element=NULL;
    }

    raptor_xml_writer_raw_counted(xml_writer, (const unsigned char*)"    ", 4);
    raptor_xml_writer_end_element(xml_writer, result_element);
    raptor_xml_writer_raw_counted(xml_writer, (const unsigned char*)"\n", 1);
    
    rasqal_query_results_next(results);
  }

  raptor_xml_writer_raw_counted(xml_writer, (const unsigned char*)"  ", 2);
  raptor_xml_writer_end_element(xml_writer, results_element);
  raptor_xml_writer_raw_counted(xml_writer, (const unsigned char*)"\n", 1);

  results3done:

  rc=0;

  raptor_xml_writer_end_element(xml_writer, sparql_element);
  raptor_xml_writer_raw_counted(xml_writer, (const unsigned char*)"\n", 1);

  tidy:
  if(element1)
    raptor_free_xml_element(element1);
  if(variable_element)
    raptor_free_xml_element(variable_element);
  if(binding_element)
    raptor_free_xml_element(binding_element);
  if(result_element)
    raptor_free_xml_element(result_element);
  if(results_element)
    raptor_free_xml_element(results_element);
  if(sparql_element)
    raptor_free_xml_element(sparql_element);
  if(res_ns)
    raptor_free_namespace(res_ns);
  if(xml_writer)
    raptor_free_xml_writer(xml_writer);
  if(nstack)
    raptor_free_namespaces(nstack);

  return rc;
}
Example #24
0
int
main(int argc, char *argv[]) 
{
  raptor_world *world;
  const char *program = raptor_basename(argv[0]);
  raptor_iostream *iostr;
  raptor_namespace_stack *nstack;
  raptor_namespace* foo_ns;
  raptor_xml_writer* xml_writer;
  raptor_uri* base_uri;
  raptor_qname* el_name;
  raptor_xml_element *element;
  unsigned long offset;
  raptor_qname **attrs;
  raptor_uri* base_uri_copy = NULL;

  /* for raptor_new_iostream_to_string */
  void *string = NULL;
  size_t string_len = 0;

  world = raptor_new_world();
  if(!world || raptor_world_open(world))
    exit(1);
  
  iostr = raptor_new_iostream_to_string(world, &string, &string_len, NULL);
  if(!iostr) {
    fprintf(stderr, "%s: Failed to create iostream to string\n", program);
    exit(1);
  }

  nstack = raptor_new_namespaces(world, 1);

  xml_writer = raptor_new_xml_writer(world, nstack, iostr);
  if(!xml_writer) {
    fprintf(stderr, "%s: Failed to create xml_writer to iostream\n", program);
    exit(1);
  }

  base_uri = raptor_new_uri(world, base_uri_string);

  foo_ns = raptor_new_namespace(nstack,
                              (const unsigned char*)"foo",
                              (const unsigned char*)"http://example.org/foo-ns#",
                              0);


  el_name = raptor_new_qname_from_namespace_local_name(world,
                                                       foo_ns,
                                                       (const unsigned char*)"bar", 
                                                       NULL);
  base_uri_copy = base_uri ? raptor_uri_copy(base_uri) : NULL;
  element = raptor_new_xml_element(el_name,
                                  NULL, /* language */
                                  base_uri_copy);

  raptor_xml_writer_start_element(xml_writer, element);
  raptor_xml_writer_cdata_counted(xml_writer, (const unsigned char*)"hello\n", 6);
  raptor_xml_writer_comment_counted(xml_writer, (const unsigned char*)"comment", 7);
  raptor_xml_writer_cdata(xml_writer, (const unsigned char*)"\n");
  raptor_xml_writer_end_element(xml_writer, element);

  raptor_free_xml_element(element);

  raptor_xml_writer_cdata(xml_writer, (const unsigned char*)"\n");

  el_name = raptor_new_qname(nstack, 
                             (const unsigned char*)"blah", 
                             NULL /* no attribute value - element */);
  base_uri_copy = base_uri ? raptor_uri_copy(base_uri) : NULL;
  element = raptor_new_xml_element(el_name,
                                   NULL, /* language */
                                   base_uri_copy);

  attrs = (raptor_qname **)RAPTOR_CALLOC(qnamearray, 1, sizeof(raptor_qname*));
  attrs[0] = raptor_new_qname(nstack, 
                              (const unsigned char*)"a",
                              (const unsigned char*)"b" /* attribute value */);
  raptor_xml_element_set_attributes(element, attrs, 1);

  raptor_xml_writer_empty_element(xml_writer, element);

  raptor_xml_writer_cdata(xml_writer, (const unsigned char*)"\n");

  raptor_free_xml_writer(xml_writer);

  raptor_free_xml_element(element);

  raptor_free_namespace(foo_ns);

  raptor_free_namespaces(nstack);

  raptor_free_uri(base_uri);

  
  offset = raptor_iostream_tell(iostr);

#if RAPTOR_DEBUG > 1
  fprintf(stderr, "%s: Freeing iostream\n", program);
#endif
  raptor_free_iostream(iostr);

  if(offset != OUT_BYTES_COUNT) {
    fprintf(stderr, "%s: I/O stream wrote %d bytes, expected %d\n", program,
            (int)offset, (int)OUT_BYTES_COUNT);
    fputs("[[", stderr);
    (void)fwrite(string, 1, string_len, stderr);
    fputs("]]\n", stderr);
    return 1;
  }
  
  if(!string) {
    fprintf(stderr, "%s: I/O stream failed to create a string\n", program);
    return 1;
  }
  string_len = strlen((const char*)string);
  if(string_len != offset) {
    fprintf(stderr, "%s: I/O stream created a string length %d, expected %d\n", program, (int)string_len, (int)offset);
    return 1;
  }

#if RAPTOR_DEBUG > 1
  fprintf(stderr, "%s: Made XML string of %d bytes\n", program, (int)string_len);
  fputs("[[", stderr);
  (void)fwrite(string, 1, string_len, stderr);
  fputs("]]\n", stderr);
#endif

  raptor_free_memory(string);
  
  raptor_free_world(world);
  
  /* keep gcc -Wall happy */
  return(0);
}
Example #25
0
int
main(int argc, char *argv[]) 
{
  raptor_world *world;
  const char *program = raptor_basename(argv[0]);
  raptor_iostream *iostr;
  raptor_namespace_stack *nstack;
  raptor_namespace* ex_ns;
  raptor_turtle_writer* turtle_writer;
  raptor_uri* base_uri;
  raptor_qname* el_name;
  unsigned long count;
  raptor_uri* datatype;
  
  /* for raptor_new_iostream_to_string */
  void *string = NULL;
  size_t string_len = 0;

  world = raptor_new_world();
  if(!world || raptor_world_open(world))
    exit(1);
  
  iostr = raptor_new_iostream_to_string(world, &string, &string_len, NULL);
  if(!iostr) {
    fprintf(stderr, "%s: Failed to create iostream to string\n", program);
    exit(1);
  }

  nstack = raptor_new_namespaces(world, 1);

  base_uri = raptor_new_uri(world, base_uri_string);

  turtle_writer = raptor_new_turtle_writer(world, base_uri, 1, nstack, iostr);
  if(!turtle_writer) {
    fprintf(stderr, "%s: Failed to create turtle_writer to iostream\n", program);
    exit(1);
  }

  raptor_turtle_writer_set_option(turtle_writer, 
                                   RAPTOR_OPTION_WRITER_AUTO_INDENT, 1);

  ex_ns = raptor_new_namespace(nstack,
                              (const unsigned char*)"ex",
                              (const unsigned char*)"http://example.org/ns#",
                              0);


  raptor_turtle_writer_namespace_prefix(turtle_writer, ex_ns);

  raptor_turtle_writer_reference(turtle_writer, base_uri);
  
  raptor_turtle_writer_increase_indent(turtle_writer);
  raptor_turtle_writer_newline(turtle_writer);
  
  raptor_turtle_writer_raw(turtle_writer, (const unsigned char*)"ex:foo ");

  raptor_turtle_writer_quoted_counted_string(turtle_writer, longstr,
                                             strlen((const char*)longstr));
  raptor_turtle_writer_raw_counted(turtle_writer,
                                   (const unsigned char*)" ;", 2);
  raptor_turtle_writer_newline(turtle_writer);

  el_name = raptor_new_qname_from_namespace_local_name(world,
                                                       ex_ns,
                                                       (const unsigned char*)"bar", 
                                                       NULL);

  raptor_turtle_writer_qname(turtle_writer, el_name);
  raptor_free_qname(el_name);

  raptor_turtle_writer_raw_counted(turtle_writer, (const unsigned char*)" ", 1);

  datatype = raptor_new_uri(world, (const unsigned char*)"http://www.w3.org/2001/XMLSchema#decimal");
  raptor_turtle_writer_literal(turtle_writer, nstack,
                               (const unsigned char*)"10.0", NULL,
                               datatype);
  raptor_free_uri(datatype);

  raptor_turtle_writer_newline(turtle_writer);

  raptor_turtle_writer_decrease_indent(turtle_writer);

  raptor_turtle_writer_raw_counted(turtle_writer, (const unsigned char*)".", 1);
  raptor_turtle_writer_newline(turtle_writer);

  
  raptor_free_turtle_writer(turtle_writer);

  raptor_free_namespace(ex_ns);

  raptor_free_namespaces(nstack);

  raptor_free_uri(base_uri);

  
  count = raptor_iostream_tell(iostr);

#if RAPTOR_DEBUG > 1
  fprintf(stderr, "%s: Freeing iostream\n", program);
#endif
  raptor_free_iostream(iostr);

  if(count != OUT_BYTES_COUNT) {
    fprintf(stderr, "%s: I/O stream wrote %d bytes, expected %d\n", program,
            (int)count, (int)OUT_BYTES_COUNT);
    fputs("[[", stderr);
    (void)fwrite(string, 1, string_len, stderr);
    fputs("]]\n", stderr);
    return 1;
  }
  
  if(!string) {
    fprintf(stderr, "%s: I/O stream failed to create a string\n", program);
    return 1;
  }
  string_len = strlen((const char*)string);
  if(string_len != count) {
    fprintf(stderr, "%s: I/O stream created a string length %d, expected %d\n", program, (int)string_len, (int)count);
    return 1;
  }

#if RAPTOR_DEBUG > 1
  fprintf(stderr, "%s: Made Turtle string of %d bytes\n", program, (int)string_len);
  fputs("[[", stderr);
  (void)fwrite(string, 1, string_len, stderr);
  fputs("]]\n", stderr);
#endif

  raptor_free_memory(string);

  raptor_free_world(world);

  /* keep gcc -Wall happy */
  return(0);
}