Exemplo n.º 1
0
static int
print_graph_result(rasqal_query* rq,
                   rasqal_query_results *results,
                   raptor_world* raptor_world_ptr,
                   FILE* output,
                   const char* serializer_syntax_name, raptor_uri* base_uri,
                   int quiet)
{
    int triple_count = 0;
    rasqal_prefix* prefix;
    int i;
    raptor_serializer* serializer = NULL;

    if(!quiet)
        fprintf(stderr, "%s: Query has a graph result:\n", program);

    if(!raptor_world_is_serializer_name(raptor_world_ptr, serializer_syntax_name)) {
        fprintf(stderr,
                "%s: invalid query result serializer name `%s' for `" HELP_ARG(r, results) "'\n",
                program, serializer_syntax_name);
        return 1;
    }

    serializer = raptor_new_serializer(raptor_world_ptr,
                                       serializer_syntax_name);
    if(!serializer) {
        fprintf(stderr, "%s: Failed to create raptor serializer type %s\n",
                program, serializer_syntax_name);
        return(1);
    }

    /* Declare any query namespaces in the output serializer */
    for(i = 0; (prefix = rasqal_query_get_prefix(rq, i)); i++)
        raptor_serializer_set_namespace(serializer, prefix->uri, prefix->prefix);
    raptor_serializer_start_to_file_handle(serializer, base_uri, output);

    while(1) {
        raptor_statement *rs = rasqal_query_results_get_triple(results);
        if(!rs)
            break;

        raptor_serializer_serialize_statement(serializer, rs);
        triple_count++;

        if(rasqal_query_results_next_triple(results))
            break;
    }

    raptor_serializer_serialize_end(serializer);
    raptor_free_serializer(serializer);

    if(!quiet)
        fprintf(stderr, "%s: Total %d triples\n", program, triple_count);

    return 0;
}
Exemplo n.º 2
0
int
main(int argc, char *argv[]) 
{
  raptor_parser* rdf_parser=NULL;
  unsigned char *uri_string=NULL;
  int free_uri_string=0;
  unsigned char *base_uri_string=NULL;
  int rc;
  int scanning=0;
  const char *syntax_name="rdfxml";
  int strict_mode=0;
  int usage=0;
  int help=0;
  raptor_uri *base_uri;
  raptor_uri *uri;
  char *p;
  char *filename=NULL;

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

  raptor_init();
  
  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 'a':
        break;

      case 'c':
        count=1;
        break;

      case 'h':
        help=1;
        break;

      case 'n':
        syntax_name="ntriples";
        break;

      case 's':
        scanning=1;
        break;

      case 'q':
        quiet=1;
        break;

      case 'r':
        replace_newlines=1;
        break;

      case 'm':
        if(optarg) {
          if(!strcmp(optarg, "strict"))
            strict_mode=1;
          else if (!strcmp(optarg, "lax"))
            strict_mode=0;
          else {
            fprintf(stderr, "%s: invalid argument `%s' for `" HELP_ARG(m, mode) "'\n",
                    program, optarg);
            fprintf(stderr, "Valid arguments are:\n  - `lax'\n  - `strict'\n");
            usage=1;
          }
        }
        break;

      case 'o':
        if(optarg) {
          if(!strcmp(optarg, "simple"))
            output_format=OUTPUT_FORMAT_SIMPLE;
          else if (!strcmp(optarg, "ntriples"))
            output_format=OUTPUT_FORMAT_NTRIPLES;
          else {
            fprintf(stderr, "%s: invalid argument `%s' for `" HELP_ARG(o, output) "'\n",
                    program, optarg);
            fprintf(stderr, "Valid arguments are:\n  `simple'   for a simple format (default)\n  `ntriples' for N-Triples\n");
            usage=1;
          }
        }
        break;

      case 'i':
        if(optarg) {
          if(raptor_syntax_name_check(optarg))
            syntax_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 char *help_name;
              const char *help_label;
              if(raptor_syntaxes_enumerate(i, &help_name, &help_label, NULL, NULL))
                break;
              printf("  %-12s for %s\n", help_name, help_label);
            }
            usage=1;
            break;
            
          }
        }
        break;

      case 'w':
        ignore_warnings=1;
        break;
        
      case 'e':
        ignore_errors=1;
        break;

      case 'v':
        fputs(raptor_version_string, stdout);
        fputc('\n', stdout);
        exit(0);
    }
    
  }

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

  
  if(usage) {
    if(usage>1) {
      fprintf(stderr, title_format_string, raptor_version_string);
      fputs(raptor_short_copyright_string, stderr);
      fputc('\n', stderr);
    }
    fprintf(stderr, "Try `%s " HELP_ARG(h, help) "' for more information.\n",
                    program);
    exit(1);
  }

  if(help) {
    int i;
    
    printf("Usage: %s [OPTIONS] <source URI> [base URI]\n", program);
    printf(title_format_string, raptor_version_string);
    puts(raptor_short_copyright_string);
    puts("Parse RDF content at the source URI into RDF triples.");
    puts("\nMain options:");
    puts(HELP_TEXT(h, "help            ", "Print this help, then exit"));
    puts(HELP_TEXT(i, "input FORMAT    ", "Set input format to one of:"));
    for(i=0; 1; i++) {
      const char *help_name;
      const char *help_label;
      if(raptor_syntaxes_enumerate(i, &help_name, &help_label, NULL, NULL))
        break;
      printf("    %-12s            %s", help_name, help_label);
      if(!i)
        puts(" (default)");
      else
        putchar('\n');
    }
    puts(HELP_TEXT(o, "output FORMAT   ", "Set output format to one of:"));
    puts("    'simple'                A simple format (default)\n    'ntriples'              N-Triples");
    puts(HELP_TEXT(m, "mode MODE       ", "Set parser mode - 'lax' (default) or 'strict'"));
    puts("\nAdditional options:");
    puts(HELP_TEXT(c, "count           ", "Count triples - no output"));
    puts(HELP_TEXT(e, "ignore-errors   ", "Ignore error messages"));
    puts(HELP_TEXT(q, "quiet           ", "No extra information messages"));
    puts(HELP_TEXT(r, "replace-newlines", "Replace newlines with spaces in literals"));
    puts(HELP_TEXT(s, "scan            ", "Scan for <rdf:RDF> element in source"));
    puts(HELP_TEXT(w, "ignore-warnings ", "Ignore warning messages"));
    puts(HELP_TEXT(v, "version         ", "Print the Raptor version"));
    puts("\nReport bugs to <*****@*****.**>.");
    puts("Raptor home page: http://www.redland.opensource.ac.uk/raptor/");
    exit(0);
  }


  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(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) {
    base_uri=raptor_uri_copy(uri);
  } else {
    base_uri=raptor_new_uri(base_uri_string);
    if(!base_uri) {
      fprintf(stderr, "%s: Failed to create URI for %s\n",
              program, base_uri_string);
      return(1);
    }
  }

  rdf_parser=raptor_new_parser(syntax_name);
  if(!rdf_parser) {
    fprintf(stderr, "%s: Failed to create raptor parser type %s\n", program,
            syntax_name);
    return(1);
  }
  
  raptor_set_error_handler(rdf_parser, rdf_parser, rdfdump_error_handler);
  raptor_set_warning_handler(rdf_parser, rdf_parser, rdfdump_warning_handler);
  
  raptor_set_parser_strict(rdf_parser, strict_mode);
  
  if(scanning)
    raptor_set_feature(rdf_parser, RAPTOR_FEATURE_SCANNING, 1);

  if(!quiet) {
    if (filename) {
      if(base_uri_string)
        fprintf(stdout, "%s: Parsing file %s with base URI %s\n", program,
                filename, base_uri_string);
      else
        fprintf(stdout, "%s: Parsing file %s\n", program, filename);
    } else {
      if(base_uri_string)
        fprintf(stdout, "%s: Parsing URI %s with base URI %s\n", program,
                uri_string, base_uri_string);
      else
        fprintf(stdout, "%s: Parsing URI %s\n", program, uri_string);
    }
  }
  
  raptor_set_statement_handler(rdf_parser, NULL, print_statements);


  /* PARSE the URI as RDF/XML */
  rc=0;
  if(!uri || filename) {
    if(raptor_parse_file(rdf_parser, uri, base_uri)) {
      fprintf(stderr, "%s: Failed to parse file %s %s content\n", program, 
              filename, syntax_name);
      rc=1;
    }
  } else {
    if(raptor_parse_uri(rdf_parser, uri, base_uri)) {
      fprintf(stderr, "%s: Failed to parse URI %s %s content\n", program, 
              uri_string, syntax_name);
      rc=1;
    }
  }

  raptor_free_parser(rdf_parser);

  if(!quiet)
    fprintf(stdout, "%s: Parsing returned %d statements\n", program,
            statement_count);

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

  raptor_finish();

  if(error_count && !ignore_errors)
    return 1;

  if(warning_count && !ignore_warnings)
    return 2;

  return(rc);
}
Exemplo n.º 3
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);
}
Exemplo n.º 4
0
int
main(int argc, char *argv[]) 
{
  flickcurl *fc = NULL;
  int rc = 0;
  int usage = 0;
  int help = 0;
  const char* home;
  char config_path[1024];
  char* photo_id = NULL;
  const char* prefix_uri = "http://www.flickr.com/photos/";
  size_t prefix_uri_len = strlen(prefix_uri);
  const char *serializer_syntax_name = "ntriples";
  raptor_uri* base_uri = NULL;
  raptor_serializer* serializer = NULL;
  int request_delay= -1;
  flickcurl_serializer* fs = NULL;
  flickcurl_photo* photo = NULL;

  program = my_basename(argv[0]);

  flickcurl_init();

  rworld = raptor_new_world();
  raptor_world_open(rworld);

  home = getenv("HOME");
  if(home)
    sprintf(config_path, "%s/%s", home, config_filename);
  else
    strcpy(config_path, config_filename);
  

  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':
        if(optarg)
          request_delay = atoi(optarg);
        break;
        
      case 'D':
        debug = 1;
        break;
        
      case 'h':
        help = 1;
        break;

      case 'o':
        if(optarg) {
          if(raptor_world_is_serializer_name(rworld, optarg))
            serializer_syntax_name = optarg;
          else {
            int i;
            
            fprintf(stderr,
                    "%s: invalid argument `%s' for `" HELP_ARG(o, output) "'\n",
                    program, optarg);
            fprintf(stderr, "Valid arguments are:\n");
            for(i = 0; 1; i++) {
              const raptor_syntax_description *d;

              d = raptor_world_get_serializer_description(rworld, i);
              if(!d)
                break;
              printf("  %-12s for %s\n", d->names[0], d->label);
            }
            usage = 1;
            break;
            
          }
        }
        break;
        
      case 'v':
        fputs(flickcurl_version_string, stdout);
        fputc('\n', stdout);

        exit(0);
    }
    
  }

  argv+= optind;
  argc-= optind;
  
  if(!help && argc < 1)
    usage = 2; /* Title and usage */

  if(!help && !argc) {
    fprintf(stderr, "%s: No photo URI given\n", program);
    usage = 1;
    goto usage;
  }

  if(usage || help)
    goto usage;

  photo_id = argv[0];
  if(strncmp(photo_id, prefix_uri, prefix_uri_len))
    usage = 1;
  else {
    size_t len;

    photo_id+= prefix_uri_len;
    len = strlen(photo_id);
    if(!len)
      usage = 1;
    else {
      if(photo_id[len-1] == '/')
        photo_id[--len] = '\0';
      
      while(*photo_id && *photo_id != '/')
        photo_id++;
      if(!*photo_id)
        usage = 1;
      else
        photo_id++;
    }
  }

  if(usage) {
    fprintf(stderr,
            "%s: Argument is not a Flickr photo URI like\n"
            "  http://www.flickr.com/photos/USER/PHOTO/\n", 
            program);
    goto usage;
  }


  serializer = raptor_new_serializer(rworld, serializer_syntax_name);
  if(!serializer) {
    fprintf(stderr, 
            "%s: Failed to create raptor serializer type %s\n", program,
            serializer_syntax_name);
    return(1);
  }

  base_uri = raptor_new_uri(rworld, (const unsigned char*)argv[0]);

  raptor_serializer_start_to_file_handle(serializer, base_uri, stdout);


  /* Initialise the Flickcurl library */
  fc = flickcurl_new();
  if(!fc) {
    rc = 1;
    goto tidy;
  }

  flickcurl_set_error_handler(fc, my_message_handler, NULL);

  if(!access((const char*)config_path, R_OK)) {
    if(flickcurl_config_read_ini(fc, config_path, config_section, fc,
                                 flickcurl_config_var_handler)) {
      rc = 1;
      goto tidy;
    }
  }
  
 usage:
  if(usage) {
    if(usage>1) {
      fprintf(stderr, title_format_string, flickcurl_version_string);
      fputs("Flickcurl home page: ", stderr);
      fputs(flickcurl_home_url_string, stderr);
      fputc('\n', stderr);
      fputs(flickcurl_copyright_string, stderr);
      fputs("\nLicense: ", stderr);
      fputs(flickcurl_license_string, stderr);
      fputs("\n\n", stderr);
    }
    fprintf(stderr, "Try `%s " HELP_ARG(h, help) "' for more information.\n",
            program);
    rc = 1;
    goto tidy;
  }

  if(help) {
    int i;

    printf(title_format_string, flickcurl_version_string);
    puts("Get Triples from Flickr photos.");
    printf("Usage: %s [OPTIONS] FLICKR-PHOTO-URI\n\n", program);

    fputs(flickcurl_copyright_string, stdout);
    fputs("\nLicense: ", stdout);
    puts(flickcurl_license_string);
    fputs("Flickcurl home page: ", stdout);
    puts(flickcurl_home_url_string);

    fputs("\n", stdout);

    puts(HELP_TEXT("d", "delay DELAY     ", "Set delay between requests in milliseconds"));
    puts(HELP_TEXT("D", "debug           ", "Print lots of output"));
    puts(HELP_TEXT("h", "help            ", "Print this help, then exit"));
    puts(HELP_TEXT("o", "output FORMAT   ", "Set output format to one of:"));
    for(i = 0; 1; i++) {
      const raptor_syntax_description* d;

      d = raptor_world_get_serializer_description(rworld, i);
      if(!d)
        break;

      if(!strcmp(d->names[0], serializer_syntax_name))
        printf("      %-15s %s (default)\n", d->names[0], d->label);
      else
        printf("      %-15s %s\n", d->names[0], d->label);
    }
#ifdef HAVE_RAPTOR
    printf("    via Raptor %s serializers\n", raptor_version_string);
#else
    puts("    via internal RDF serializer");
#endif
    puts(HELP_TEXT("v", "version         ", "Print the flickcurl version"));

    rc = 0;
    goto tidy;
  }


  if(request_delay >= 0)
    flickcurl_set_request_delay(fc, request_delay);
  
  fs = flickcurl_new_serializer(fc, serializer, &flickrdf_serializer_factory);
  if(!fs) {
    fprintf(stderr, "%s: Failed to create Flickcurl serializer\n", program);
    goto tidy;
  }
  
  photo = flickcurl_photos_getInfo(fc, photo_id);

  if(!photo)
    goto tidy;

  if(debug)
    fprintf(stderr, "%s: Photo with URI %s ID %s has %d tags\n",
            program, photo->uri, photo->id, photo->tags_count);

  rc = flickcurl_serialize_photo(fs, photo);

 tidy:
  if(photo)
    flickcurl_free_photo(photo);

  if(fs)
    flickcurl_free_serializer(fs);

  if(fc)
    flickcurl_free(fc);

  if(serializer)
    raptor_free_serializer(serializer);
  if(base_uri)
    raptor_free_uri(base_uri);

  if(rworld)
    raptor_free_world(rworld);

  flickcurl_finish();

  return(rc);
}
Exemplo n.º 5
0
int
main(int argc, char *argv[]) 
{
  flickcurl *fc = NULL;
  int rc = 0;
  int usage = 0;
  int help = 0;
  int read_auth = 1;
  int i;
  const char* home;
  char config_path[1024];
  int request_delay= -1;
  char section[50];
  size_t section_len;
  char** methods = NULL;
  
  flickcurl_init();
  
  program = my_basename(argv[0]);

  home = getenv("HOME");
  if(home)
    sprintf(config_path, "%s/%s", home, config_filename);
  else
    strcpy(config_path, config_filename);
  

  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':
        if(optarg)
          request_delay = atoi(optarg);
        break;
        
      case 'h':
        help = 1;
        break;

      case 'v':
        fputs(flickcurl_version_string, stdout);
        fputc('\n', stdout);

        exit(0);
    }
    
  }
  
  if(help)
    goto help;
  
  if(argc < 2) {
    fprintf(stderr, "%s: No API section given\n", program);
    usage = 1;
  }

  if(usage) {
    if(usage>1) {
      fprintf(stderr, title_format_string, flickcurl_version_string);
      fputs("Flickcurl home page: ", stderr);
      fputs(flickcurl_home_url_string, stderr);
      fputc('\n', stderr);
      fputs(flickcurl_copyright_string, stderr);
      fputs("\nLicense: ", stderr);
      fputs(flickcurl_license_string, stderr);
      fputs("\n\n", stderr);
    }
    fprintf(stderr, "Try `%s " HELP_ARG(h, help) "' for more information.\n",
            program);
    rc = 1;
    goto tidy;
  }

  help:
  if(help) {
    printf(title_format_string, flickcurl_version_string);
    puts("Generate C code from Flickr API by reflection.");
    printf("Usage: %s [OPTIONS] command args...\n\n", program);

    fputs(flickcurl_copyright_string, stdout);
    fputs("\nLicense: ", stdout);
    puts(flickcurl_license_string);
    fputs("Flickcurl home page: ", stdout);
    puts(flickcurl_home_url_string);

    fputs("\n", stdout);

    puts(HELP_TEXT("d", "delay DELAY     ", "Set delay between requests in milliseconds"));
    puts(HELP_TEXT("h", "help            ", "Print this help, then exit"));
    puts(HELP_TEXT("v", "version         ", "Print the flickcurl version"));

    rc = 0;
    goto tidy;
  }


  /* Initialise the Flickcurl library */
  fc = flickcurl_new();
  if(!fc) {
    rc = 1;
    goto tidy;
  }

  flickcurl_set_error_handler(fc, my_message_handler, NULL);

  if(read_auth && !access((const char*)config_path, R_OK)) {
    if(read_ini_config(config_path, config_section, fc,
                       my_set_config_var_handler)) {
      fprintf(stderr, "%s: Failed to read config filename %s: %s\n",
              program, config_path, strerror(errno));
      rc = 1;
      goto tidy;
    }
  }

  if(request_delay >= 0)
    flickcurl_set_request_delay(fc, request_delay);

  strcpy(section, "flickr.");
  strcpy(section+7, argv[1]);
  
  /* allow old format commands to work */
  for(i = 0; section[i]; i++) {
    if(section[i] == '-')
      section[i] = '.';
  }
  
  if(!strncmp(section, "flickr.flickr", 13))
    strcpy(section, section+7);
  section_len = strlen(section);
  
  fprintf(stderr, "%s: section '%s'\n", program, section);
    
  methods = flickcurl_reflection_getMethods(fc);
  if(!methods) {
    fprintf(stderr, "%s: getMethods failed\n", program);
    rc = 1;
    goto tidy;
  }

  fprintf(stdout,
"/* -*- Mode: c; c-basic-offset: 2 -*-\n"
" *\n"
" * %s-api.c - Flickr %s.* API calls\n"
" *\n",
          argv[1], section);

  fprintf(stdout,
" * Copyright (C) 2010, David Beckett http://www.dajobe.org/\n"
" * \n"
" * This file is licensed under the following three licenses as alternatives:\n"
" *   1. GNU Lesser General Public License (LGPL) V2.1 or any newer version\n"
" *   2. GNU General Public License (GPL) V2 or any newer version\n"
" *   3. Apache License, V2.0 or any newer version\n"
" * \n"
" * You may not use this file except in compliance with at least one of\n"
" * the above three licenses.\n"
" * \n"
" * See LICENSE.html or LICENSE.txt at the top of this package for the\n"
" * complete terms and further detail along with the license texts for\n"
" * the licenses in COPYING.LIB, COPYING and LICENSE-2.0.txt respectively.\n"
" * \n"
" */\n"
"\n"
"#include <stdio.h>\n"
"#include <string.h>\n"
"#include <stdarg.h>\n"
"\n"
"#ifdef HAVE_CONFIG_H\n"
"#include <config.h>\n"
"#endif\n"
"\n"
"#ifdef HAVE_STDLIB_H\n"
"#include <stdlib.h>\n"
"#undef HAVE_STDLIB_H\n"
"#endif\n"
"#ifdef HAVE_UNISTD_H\n"
"#include <unistd.h>\n"
"#endif\n"
"\n"
"#include <flickcurl.h>\n"
"#include <flickcurl_internal.h>\n"
"\n"
"\n"
          );

  
  for(i = 0; methods[i]; i++) {
    flickcurl_method* method;
    char* method_name;
    char function_name[100];
    int c, j;
    int is_write = 0;
    
    if(strncmp(methods[i], section, section_len))
      continue;
    
    method = flickcurl_reflection_getMethodInfo(fc, methods[i]);
    if(!method) {
      fprintf(stderr, "%s: getMethodInfo(%s) failed\n", program, methods[i]);
      rc = 1;
      break;
    }

    method_name = method->name;

    if(
      strstr(method_name, ".add") ||
      strstr(method_name, ".create") ||
      strstr(method_name, ".delete") ||
      strstr(method_name, ".edit") ||
      strstr(method_name, ".remove") ||
      strstr(method_name, ".set")
       )
      is_write = 1;
    
    strcpy(function_name, "flickcurl_");
    for(j = 0; (c = methods[i][j+7]); j++) {
      if(c == '.')
        c = '_';
      function_name[j+10] = c;
    }
    function_name[j+10] = '\0';

    fprintf(stdout, "/**\n * %s:\n", function_name);

    /* fixed arguments */
    fprintf(stdout, " * @fc: flickcurl context\n");

    if(method->args_count) {
      int argi;
      for(argi = 0; method->args[argi]; argi++) {
        flickcurl_arg* arg = method->args[argi];
        if(!strcmp(arg->name, "api_key"))
          continue;

        fprintf(stdout, " * @%s: %s", arg->name, arg->description);
        if(arg->optional) {
          fputs((IS_INT_ARG(arg)? " (or < 0)" : " (or NULL)"), stdout);
        }
        fputc('\n', stdout);

      }
    }

    fprintf(stdout,
" * \n"
" * %s\n"
" *\n"
" * Implements %s (%s)\n",
            method->description, method->name, flickcurl_version_string
           );

    fprintf(stdout,
" * \n"
" * Return value: non-0 on failure\n"
" **/\n"
           );
      
    fprintf(stdout, "int\n%s(flickcurl* fc", function_name);
    if(method->args_count) {
      int argi;
      for(argi = 0; method->args[argi]; argi++) {
        flickcurl_arg* arg = method->args[argi];
        if(!strcmp(arg->name, "api_key"))
          continue;
        
        if(IS_INT_ARG(arg)) {
          fprintf(stdout, ", int %s", arg->name);
        } else {
          fprintf(stdout, ", const char* %s", arg->name);
        }
      }
    }
    fprintf(stdout, ")\n{\n");

    fprintf(stdout,
"  const char* parameters[%d][2];\n"
"  int count = 0;\n"
"  xmlDocPtr doc = NULL;\n"
"  xmlXPathContextPtr xpathCtx = NULL; \n"
"  void* result = NULL;\n",
  6+method->args_count);
    if(method->args_count) {
      int argi;
      for(argi = 0; method->args[argi]; argi++) {
        flickcurl_arg* arg = method->args[argi];
        if(IS_INT_ARG(arg)) {
          fprintf(stdout,
"  char %s_str[10];\n",
                  arg->name);
        }
      }
    }

    fputs(
"  \n",
    stdout);
    
    
    if(method->args_count) {
      int argi;
      int print_or = 0;
      
      fprintf(stdout, "  if(");
      for(argi = 0; method->args[argi]; argi++) {
        flickcurl_arg* arg = method->args[argi];
        if(!strcmp(arg->name, "api_key"))
          continue;
        
        if(!arg->optional) {
          if(print_or)
            fprintf(stdout, " || ");
          
          fprintf(stdout, "!%s", arg->name);
          print_or = 1;
        }
      }
      fprintf(stdout,
")\n"
"    return 1;\n"
"\n");
    }


    if(method->args_count) {
      int argi;
      for(argi = 0; method->args[argi]; argi++) {
        flickcurl_arg* arg = method->args[argi];
        if(!strcmp(arg->name, "api_key"))
          continue;
        
        if(arg->optional) {
          if(IS_INT_ARG(arg)) {
            fprintf(stdout,
"  if(%s >= 0) {\n"
"    sprintf(%s_str, \"%%d\", %s);\n"
"    parameters[count][0]  = \"%s\";\n"
"    parameters[count++][1]= %s_str;\n"
"  }\n",
                    arg->name, arg->name, arg->name, arg->name, arg->name);
            continue;
          }
          fprintf(stdout,
"  if(%s) {\n",
                  arg->name);
        }
        
        fprintf(stdout,
"  parameters[count][0]  = \"%s\";\n"
"  parameters[count++][1]= %s;\n",
              arg->name, arg->name);

        if(arg->optional) {
          fprintf(stdout,
"  }\n"
                  );
        }
        
      }
    }

    fprintf(stdout,
"\n"
"  parameters[count][0]  = NULL;\n"
"\n"
            );

    fprintf(stdout,
"  if(flickcurl_prepare(fc, \"%s\", parameters, count))\n"
"    goto tidy;\n"
"\n",
    method->name);

    if(is_write)
      fprintf(stdout, 
"  flickcurl_set_write(fc, 1);\n"
"  flickcurl_set_data(fc, (void*)\"\", 0);\n"
"\n"
);

    fprintf(stdout,
"  doc = flickcurl_invoke(fc);\n"
"  if(!doc)\n"
"    goto tidy;\n"
"\n"
"\n"
"  xpathCtx = xmlXPathNewContext(doc);\n"
"  if(!xpathCtx) {\n"
"    flickcurl_error(fc, \"Failed to create XPath context for document\");\n"
"    fc->failed = 1;\n"
"    goto tidy;\n"
"  }\n"
"\n"
"  result = NULL; /* your code here */\n"
"\n"
"  tidy:\n"
"  if(xpathCtx)\n"
"    xmlXPathFreeContext(xpathCtx);\n"
"\n"
"  if(fc->failed)\n"
"    result = NULL;\n"
"\n"
"  return (result == NULL);\n"
"}\n"
"\n"
"\n");

    flickcurl_free_method(method);
  }


 tidy:
  if(methods) {
    for(i = 0; methods[i]; i++)
      free(methods[i]);
    free(methods);
    methods = NULL;
  }

  if(fc)
    flickcurl_free(fc);

  flickcurl_finish();

  return(rc);
}
Exemplo n.º 6
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);
}
Exemplo n.º 7
0
int
main(int argc, char *argv[]) 
{
  flickcurl *fc = NULL;
  int rc = 0;
  int usage = 0;
  int help = 0;
  int read_auth = 1;
  int i;
  const char* home;
  char config_path[1024];
  char** methods = NULL;
  int count = 0;
  
  flickcurl_init();
  
  program = my_basename(argv[0]);

  home = getenv("HOME");
  if(home)
    sprintf(config_path, "%s/%s", home, config_filename);
  else
    strcpy(config_path, config_filename);
  

  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 'h':
        help = 1;
        break;

      case 'v':
        fputs(flickcurl_version_string, stdout);
        fputc('\n', stdout);

        exit(0);
    }
    
  }
  
  if(help)
    goto help;
  
  if(argc != 1) {
    fprintf(stderr, "%s: Extra arguments given\n", program);
    usage = 1;
  }

  if(usage) {
    if(usage>1) {
      fprintf(stderr, title_format_string, flickcurl_version_string);
      fputs("Flickcurl home page: ", stderr);
      fputs(flickcurl_home_url_string, stderr);
      fputc('\n', stderr);
      fputs(flickcurl_copyright_string, stderr);
      fputs("\nLicense: ", stderr);
      fputs(flickcurl_license_string, stderr);
      fputs("\n\n", stderr);
    }
    fprintf(stderr, "Try `%s " HELP_ARG(h, help) "' for more information.\n",
            program);
    rc = 1;
    goto tidy;
  }

  help:
  if(help) {
    printf(title_format_string, flickcurl_version_string);
    puts("List Flickr API methods by reflection.");
    printf("Usage: %s [OPTIONS]\n\n", program);

    fputs(flickcurl_copyright_string, stdout);
    fputs("\nLicense: ", stdout);
    puts(flickcurl_license_string);
    fputs("Flickcurl home page: ", stdout);
    puts(flickcurl_home_url_string);

    fputs("\n", stdout);

    puts(HELP_TEXT("h", "help            ", "Print this help, then exit"));
    puts(HELP_TEXT("v", "version         ", "Print the flickcurl version"));

    rc = 0;
    goto tidy;
  }


  /* Initialise the Flickcurl library */
  fc = flickcurl_new();
  if(!fc) {
    rc = 1;
    goto tidy;
  }

  flickcurl_set_error_handler(fc, my_message_handler, NULL);

  if(read_auth && !access((const char*)config_path, R_OK)) {
    if(flickcurl_config_read_ini(fc, config_path, config_section, fc,
                                 flickcurl_config_var_handler)) {
      rc = 1;
      goto tidy;
    }
  }

  methods = flickcurl_reflection_getMethods(fc);
  if(!methods) {
    fprintf(stderr, "%s: getMethods failed\n", program);
    rc = 1;
    goto tidy;
  }

  for(i = 0; methods[i]; i++)
    ;
  count = i;
  
  fprintf(stderr, "%s: Found %d API methods\n", program, count);
  
  /* it seems to be sorted when returned but ensure it anyway */
  qsort(methods, count, sizeof(char*), compare_strings);
  
  for(i = 0; methods[i]; i++) {
    fputs((const char*)methods[i], stdout);
    fputc('\n', stdout);
  }


 tidy:
  if(methods) {
    for(i = 0; methods[i]; i++)
      free(methods[i]);
    free(methods);
    methods = NULL;
  }

  if(fc)
    flickcurl_free(fc);

  flickcurl_finish();

  return(rc);
}