File: rdfextract.cpp

package info (click to toggle)
musicbrainz 1.0.1.final-2
  • links: PTS
  • area: main
  • in suites: woody
  • size: 2,168 kB
  • ctags: 2,610
  • sloc: ansic: 16,052; sh: 8,658; cpp: 6,283; perl: 327; makefile: 112
file content (316 lines) | stat: -rw-r--r-- 9,016 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
/* --------------------------------------------------------------------------

   MusicBrainz -- The Internet music metadatabase

   Copyright (C) 2000 Robert Kaye
   
   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.
   
   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.
   
   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

     $Id: rdfextract.cpp,v 1.4 2001/04/18 03:21:03 robert Exp $

----------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <list>
#include "rdfextract.h"

#undef DEBUG

void statement_handler(void*           user_data,
                       RDF_SubjectType subject_type,
                       const XML_Char* subject,
                       const XML_Char* predicate,
                       int             ordinal,
                       RDF_ObjectType  object_type,
                       const XML_Char* object,
                       const XML_Char* xml_lang)
{
    ((RDFExtract *)user_data)->StatementHandler(subject_type,
        subject, predicate, ordinal, object_type, object);
}

RDFExtract::RDFExtract(const string &rdfDocument, bool useUTF8)
{
   RDF_Parser parser;

   hasError = false;
   this->useUTF8 = useUTF8;

   parser = RDF_ParserCreate(NULL);
   RDF_SetUserData(parser, (void *)this);
   RDF_SetStatementHandler(parser, statement_handler);
   RDF_SetBase(parser, "musicbrainz");
   if (!RDF_Parse(parser, rdfDocument.c_str(), rdfDocument.length(), 1))
   {
       char line[10];

       sprintf(line, " on line %d.",
               XML_GetCurrentLineNumber(RDF_GetXmlParser(parser)));
       error = string("Error: ") + 
               string(XML_ErrorString(XML_GetErrorCode(
                      RDF_GetXmlParser(parser)))) +
               string(line);
       hasError = true;
   }
}

RDFExtract::~RDFExtract(void)
{

}

void RDFExtract::StatementHandler(RDF_SubjectType subject_type,
                                  const XML_Char* subject,
                                  const XML_Char* predicate,
                                  int             ordinal,
                                  RDF_ObjectType  object_type,
                                  const XML_Char* object)
{
    RDFStatement statement;

    if (useUTF8)
        statement.subject = string((char *)subject);
    else
        statement.subject = ConvertToISO(subject);

    if (useUTF8)
        statement.object = string((char *)object);
    else
        statement.object = ConvertToISO(object);

    if (ordinal == 0)
    {
        if (useUTF8)
            statement.predicate = string((char *)predicate);
        else
            statement.predicate = ConvertToISO(predicate);
        statement.ordinal = 0;
    }
    else
        statement.ordinal = ordinal;

    statement.subjectType = subject_type;
    statement.objectType = object_type;

#ifdef DEBUG
    printf("%s\n%s\n%s\n\n", 
       statement.subject.c_str(),
       statement.predicate.c_str(),
       statement.object.c_str());
#endif

    triples.push_back(statement);
}

int RDFExtract::GetNumTriples(void)
{
    return triples.size();
}

void RDFExtract::GetTriples(vector<RDFStatement> *triplesArg)
{
    *triplesArg = triples;
}

const string &RDFExtract::Extract(const string &startURI, 
                                  const string &query, 
                                  int ordinal)
{
    list<int> ordinalList;

    ordinalList.push_back(ordinal);
    return Extract(startURI, query, &ordinalList);
}

const string &RDFExtract::Extract(const string &startURI, 
                                  const string &query, 
                                  list<int> *ordinalList)
{
    vector<RDFStatement>::iterator i;
    list<string>                   predicateList;
    string                         currentURI = startURI;
    char                          *queryString, *ptr;
    bool                           done;

    if (query.length() == 0)
    {
        retValue = startURI;
        return retValue;
    }

    queryString = strdup(query.c_str());
    ptr = strtok(queryString, " \t\n");
    for(; ptr != NULL; ptr = strtok(NULL, " \t\n"))
    {
       if (strlen(ptr) > 0)
       {
          //printf("pl: '%s'\n", ptr);
          predicateList.push_back(string(ptr));
       }
    }
    free(queryString);

#ifdef DEBUG
    printf("-----------------------------------------------\n");
    printf(" Base: %s\n", startURI.c_str());
    printf("Query: %s\n\n", query.c_str());
#endif

    for(;;)
    {
       done = false;
#ifdef DEBUG
       printf("Curr URI %s: Pred: %s / [%d]\n", 
                 currentURI.c_str(),
                 (*predicateList.begin()).c_str(),
                 *(ordinalList->begin()));
#endif
       for(i = triples.begin(); i != triples.end() && !done; i++)
       {
#ifdef DEBUG
          if ((*i).subject == currentURI)
          {
              if ((*i).ordinal > 0)
                 printf("   pred: [%d]\n", (*i).ordinal);
              else
                 printf("   pred: %s\n", (*i).predicate.c_str());
          }
#endif
          //printf("Subject: '%s'\n", (*i).subject.c_str());
          if ((*i).subject == currentURI && 
             ((*i).predicate == *(predicateList.begin()) ||
             ((*i).ordinal > 0 && (*i).ordinal == *(ordinalList->begin()))))
          {
              currentURI = (*i).object;

              predicateList.pop_front();
              if ((*i).ordinal > 0)
                 ordinalList->pop_front();

              if (predicateList.size() > 0 &&
                  *(predicateList.begin()) == string("[COUNT]"))
              {
                 int num = 0;
                 char temp[10];

                 vector<RDFStatement>::iterator j;
                 for(j = triples.begin(); j != triples.end(); j++)
                 {
                    if ((*j).subject == currentURI && (*j).ordinal > 0)
                        num++;
                 }
                 sprintf(temp, "%d", num);
                 count = string(temp);
#ifdef DEBUG
                 printf("Count: %d\n\b", num);
#endif
                 return count;
              }
   
              // Force to exit the loop
              done = true;
              break;
          }
          //printf("\n");
       }
       // If we walked through all the statements and we didn't find
       // a matching predicate for the next transition, then the
       // query failed.
       if (i == triples.end())
       {
#ifdef DEBUG
          printf("-------------------------------------------\n");
          printf("Not found.\n\n");
#endif
          return empty;
       }
       // If we found a matching predicate and there are not more
       // predicate transitons, then we've arrived at the end of
       // the query. Return the last subject.
       if (done && predicateList.size() == 0)
       {
#ifdef DEBUG
          printf("-------------------------------------------\n");
          printf("Value: %s\n\n", (*i).object.c_str());
#endif
          return (*i).object;
       }
    }
}

bool RDFExtract::GetSubjectFromObject(const string &object,
                                      string       &subject)
{
    vector<RDFStatement>::iterator i;

    for(i = triples.begin(); i != triples.end(); i++)
    {
       if ((*i).object == object)
       {
           subject = (*i).subject;
           return true;
       }
    }
    return false;
}

bool RDFExtract::GetError(string &error)
{
    error = this->error;
    return error.length() > 0;
}

const string RDFExtract::ConvertToISO(const char *UTF8)
{
   unsigned char *in, *buf;
   unsigned char *out, *end;
   string               ret;

   in = (unsigned char *)UTF8;
   buf = out = new unsigned char[strlen(UTF8) + 1];
   end = in + strlen(UTF8);
   for(;*in != 0x00 && in <= end; in++, out++)
   {
       if (*in < 0x80)
       {  /* lower 7-bits unchanged */
          *out = *in;
       }
       else
       if (*in > 0xC3)
       { /* discard anything above 0xFF */
          *out = '?';
       }
       else
       if (*in & 0xC0)
       { /* parse upper 7-bits */
          if (in >= end)
            *out = 0;
          else
          {
            *out = (((*in) & 0x1F) << 6) | (0x3F & (*(++in)));
          }
       }
       else
       {
          *out = '?';  /* this should never happen */
       }
   }
   *out = 0x00; /* append null */
   ret = string((char *)buf);
   delete buf;

   return ret;
}