forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 2
/
nsRDFXMLSerializer.cpp
1159 lines (967 loc) · 35.8 KB
/
nsRDFXMLSerializer.cpp
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* vim: set ts=4 sw=4 et tw=80:
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org Code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1999
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Chris Waterson <waterson@netscape.com>
* Axel Hecht <axel@pike.org>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "nsRDFXMLSerializer.h"
#include "nsIAtom.h"
#include "nsIOutputStream.h"
#include "nsIRDFService.h"
#include "nsIRDFContainerUtils.h"
#include "nsIServiceManager.h"
#include "nsString.h"
#include "nsXPIDLString.h"
#include "nsTArray.h"
#include "rdf.h"
#include "rdfutil.h"
#include "rdfIDataSource.h"
PRInt32 nsRDFXMLSerializer::gRefCnt = 0;
nsIRDFContainerUtils* nsRDFXMLSerializer::gRDFC;
nsIRDFResource* nsRDFXMLSerializer::kRDF_instanceOf;
nsIRDFResource* nsRDFXMLSerializer::kRDF_type;
nsIRDFResource* nsRDFXMLSerializer::kRDF_nextVal;
nsIRDFResource* nsRDFXMLSerializer::kRDF_Bag;
nsIRDFResource* nsRDFXMLSerializer::kRDF_Seq;
nsIRDFResource* nsRDFXMLSerializer::kRDF_Alt;
static const char kRDFDescriptionOpen[] = " <RDF:Description";
static const char kIDAttr[] = " RDF:ID=\"";
static const char kAboutAttr[] = " RDF:about=\"";
static const char kRDFDescriptionClose[] = " </RDF:Description>\n";
static const char kRDFResource1[] = " RDF:resource=\"";
static const char kRDFResource2[] = "\"/>\n";
static const char kRDFParseTypeInteger[] = " NC:parseType=\"Integer\">";
static const char kRDFParseTypeDate[] = " NC:parseType=\"Date\">";
static const char kRDFUnknown[] = "><!-- unknown node type -->";
nsresult
nsRDFXMLSerializer::Create(nsISupports* aOuter, REFNSIID aIID, void** aResult)
{
if (aOuter)
return NS_ERROR_NO_AGGREGATION;
nsCOMPtr<nsIRDFXMLSerializer> result = new nsRDFXMLSerializer();
if (! result)
return NS_ERROR_OUT_OF_MEMORY;
// The serializer object is here, addref gRefCnt so that the
// destructor can safely release it.
gRefCnt++;
nsresult rv;
rv = result->QueryInterface(aIID, aResult);
if (NS_FAILED(rv)) return rv;
if (gRefCnt == 1) do {
nsCOMPtr<nsIRDFService> rdf = do_GetService("@mozilla.org/rdf/rdf-service;1", &rv);
if (NS_FAILED(rv)) break;
rv = rdf->GetResource(NS_LITERAL_CSTRING(RDF_NAMESPACE_URI "instanceOf"),
&kRDF_instanceOf);
if (NS_FAILED(rv)) break;
rv = rdf->GetResource(NS_LITERAL_CSTRING(RDF_NAMESPACE_URI "type"),
&kRDF_type);
if (NS_FAILED(rv)) break;
rv = rdf->GetResource(NS_LITERAL_CSTRING(RDF_NAMESPACE_URI "nextVal"),
&kRDF_nextVal);
if (NS_FAILED(rv)) break;
rv = rdf->GetResource(NS_LITERAL_CSTRING(RDF_NAMESPACE_URI "Bag"),
&kRDF_Bag);
if (NS_FAILED(rv)) break;
rv = rdf->GetResource(NS_LITERAL_CSTRING(RDF_NAMESPACE_URI "Seq"),
&kRDF_Seq);
if (NS_FAILED(rv)) break;
rv = rdf->GetResource(NS_LITERAL_CSTRING(RDF_NAMESPACE_URI "Alt"),
&kRDF_Alt);
if (NS_FAILED(rv)) break;
rv = CallGetService("@mozilla.org/rdf/container-utils;1", &gRDFC);
if (NS_FAILED(rv)) break;
} while (0);
return rv;
}
nsRDFXMLSerializer::nsRDFXMLSerializer()
{
MOZ_COUNT_CTOR(nsRDFXMLSerializer);
}
nsRDFXMLSerializer::~nsRDFXMLSerializer()
{
MOZ_COUNT_DTOR(nsRDFXMLSerializer);
if (--gRefCnt == 0) {
NS_IF_RELEASE(kRDF_Bag);
NS_IF_RELEASE(kRDF_Seq);
NS_IF_RELEASE(kRDF_Alt);
NS_IF_RELEASE(kRDF_instanceOf);
NS_IF_RELEASE(kRDF_type);
NS_IF_RELEASE(kRDF_nextVal);
NS_IF_RELEASE(gRDFC);
}
}
NS_IMPL_ISUPPORTS2(nsRDFXMLSerializer, nsIRDFXMLSerializer, nsIRDFXMLSource)
NS_IMETHODIMP
nsRDFXMLSerializer::Init(nsIRDFDataSource* aDataSource)
{
if (! aDataSource)
return NS_ERROR_NULL_POINTER;
mDataSource = aDataSource;
mDataSource->GetURI(getter_Copies(mBaseURLSpec));
// Add the ``RDF'' prefix, by default.
nsCOMPtr<nsIAtom> prefix;
prefix = do_GetAtom("RDF");
AddNameSpace(prefix, NS_LITERAL_STRING("http://www.w3.org/1999/02/22-rdf-syntax-ns#"));
prefix = do_GetAtom("NC");
AddNameSpace(prefix, NS_LITERAL_STRING("http://home.netscape.com/NC-rdf#"));
mQNames.Init();
mPrefixID = 0;
return NS_OK;
}
NS_IMETHODIMP
nsRDFXMLSerializer::AddNameSpace(nsIAtom* aPrefix, const nsAString& aURI)
{
nsCOMPtr<nsIAtom> prefix = aPrefix;
if (!prefix) {
// Make up a prefix, we don't want default namespaces, so
// that we can use QNames for elements and attributes alike.
prefix = EnsureNewPrefix();
}
mNameSpaces.Put(aURI, prefix);
return NS_OK;
}
static nsresult
rdf_BlockingWrite(nsIOutputStream* stream, const char* buf, PRUint32 size)
{
PRUint32 written = 0;
PRUint32 remaining = size;
while (remaining > 0) {
nsresult rv;
PRUint32 cb;
if (NS_FAILED(rv = stream->Write(buf + written, remaining, &cb)))
return rv;
written += cb;
remaining -= cb;
}
return NS_OK;
}
static nsresult
rdf_BlockingWrite(nsIOutputStream* stream, const nsCSubstring& s)
{
return rdf_BlockingWrite(stream, s.BeginReading(), s.Length());
}
static nsresult
rdf_BlockingWrite(nsIOutputStream* stream, const nsAString& s)
{
NS_ConvertUTF16toUTF8 utf8(s);
return rdf_BlockingWrite(stream, utf8.get(), utf8.Length());
}
already_AddRefed<nsIAtom>
nsRDFXMLSerializer::EnsureNewPrefix()
{
nsAutoString qname;
nsCOMPtr<nsIAtom> prefix;
PRBool isNewPrefix;
do {
isNewPrefix = PR_TRUE;
qname.AssignLiteral("NS");
qname.AppendInt(++mPrefixID, 10);
prefix = do_GetAtom(qname);
nsNameSpaceMap::const_iterator iter = mNameSpaces.first();
while (iter != mNameSpaces.last() && isNewPrefix) {
isNewPrefix = (iter->mPrefix != prefix);
++iter;
}
} while (!isNewPrefix);
nsIAtom* outPrefix = nsnull;
prefix.swap(outPrefix);
return outPrefix;
}
// This converts a property resource (like
// "http://www.w3.org/TR/WD-rdf-syntax#Description") into a QName
// ("RDF:Description"), and registers the namespace, if it's made up.
nsresult
nsRDFXMLSerializer::RegisterQName(nsIRDFResource* aResource)
{
nsCAutoString uri, qname;
aResource->GetValueUTF8(uri);
nsNameSpaceMap::const_iterator iter = mNameSpaces.GetNameSpaceOf(uri);
if (iter != mNameSpaces.last()) {
NS_ENSURE_TRUE(iter->mPrefix, NS_ERROR_UNEXPECTED);
iter->mPrefix->ToUTF8String(qname);
qname.Append(':');
qname += StringTail(uri, uri.Length() - iter->mURI.Length());
return mQNames.Put(aResource, qname) ? NS_OK : NS_ERROR_FAILURE;
}
// Okay, so we don't have it in our map. Try to make one up. This
// is very bogus.
PRInt32 i = uri.RFindChar('#'); // first try a '#'
if (i == -1) {
i = uri.RFindChar('/');
if (i == -1) {
// Okay, just punt and assume there is _no_ namespace on
// this thing...
return mQNames.Put(aResource, uri) ? NS_OK : NS_ERROR_FAILURE;
}
}
// Take whatever is to the right of the '#' or '/' and call it the
// local name, make up a prefix.
nsCOMPtr<nsIAtom> prefix = EnsureNewPrefix();
mNameSpaces.Put(StringHead(uri, i+1), prefix);
prefix->ToUTF8String(qname);
qname.Append(':');
qname += StringTail(uri, uri.Length() - (i + 1));
return mQNames.Put(aResource, qname) ? NS_OK : NS_ERROR_FAILURE;
}
nsresult
nsRDFXMLSerializer::GetQName(nsIRDFResource* aResource, nsCString& aQName)
{
return mQNames.Get(aResource, &aQName) ? NS_OK : NS_ERROR_UNEXPECTED;
}
PRBool
nsRDFXMLSerializer::IsContainerProperty(nsIRDFResource* aProperty)
{
// Return `true' if the property is an internal property related
// to being a container.
if (aProperty == kRDF_instanceOf)
return PR_TRUE;
if (aProperty == kRDF_nextVal)
return PR_TRUE;
PRBool isOrdinal = PR_FALSE;
gRDFC->IsOrdinalProperty(aProperty, &isOrdinal);
if (isOrdinal)
return PR_TRUE;
return PR_FALSE;
}
// convert '&', '<', and '>' into "&", "<", and ">", respectively.
static const char amp[] = "&";
static const char lt[] = "<";
static const char gt[] = ">";
static const char quot[] = """;
static void
rdf_EscapeAmpersandsAndAngleBrackets(nsCString& s)
{
PRUint32 newLength, origLength;
newLength = origLength = s.Length();
// Compute the length of the result string.
const char* start = s.BeginReading();
const char* end = s.EndReading();
const char* c = start;
while (c != end) {
switch (*c) {
case '&' :
newLength += sizeof(amp) - 2;
break;
case '<':
case '>':
newLength += sizeof(gt) - 2;
break;
default:
break;
}
++c;
}
if (newLength == origLength) {
// nothing to escape
return;
}
// escape the chars from the end back to the front.
s.SetLength(newLength);
// Buffer might have changed, get the pointers again
start = s.BeginReading(); // begin of string
c = start + origLength - 1; // last char in original string
char* w = s.EndWriting() - 1; // last char in grown buffer
while (c >= start) {
switch (*c) {
case '&' :
w -= 4;
nsCharTraits<char>::copy(w, amp, sizeof(amp) - 1);
break;
case '<':
w -= 3;
nsCharTraits<char>::copy(w, lt, sizeof(lt) - 1);
break;
case '>':
w -= 3;
nsCharTraits<char>::copy(w, gt, sizeof(gt) - 1);
break;
default:
*w = *c;
}
--w;
--c;
}
}
// convert '"' to """
static void
rdf_EscapeQuotes(nsCString& s)
{
PRInt32 i = 0;
while ((i = s.FindChar('"', i)) != -1) {
s.Replace(i, 1, quot, sizeof(quot) - 1);
i += sizeof(quot) - 2;
}
}
static void
rdf_EscapeAttributeValue(nsCString& s)
{
rdf_EscapeAmpersandsAndAngleBrackets(s);
rdf_EscapeQuotes(s);
}
nsresult
nsRDFXMLSerializer::SerializeInlineAssertion(nsIOutputStream* aStream,
nsIRDFResource* aResource,
nsIRDFResource* aProperty,
nsIRDFLiteral* aValue)
{
nsresult rv;
nsCString qname;
rv = GetQName(aProperty, qname);
NS_ENSURE_SUCCESS(rv, rv);
rv = rdf_BlockingWrite(aStream,
NS_LITERAL_CSTRING("\n "));
if (NS_FAILED(rv)) return rv;
const PRUnichar* value;
aValue->GetValueConst(&value);
NS_ConvertUTF16toUTF8 s(value);
rdf_EscapeAttributeValue(s);
rv = rdf_BlockingWrite(aStream, qname);
if (NS_FAILED(rv)) return rv;
rv = rdf_BlockingWrite(aStream, "=\"", 2);
if (NS_FAILED(rv)) return rv;
s.Append('"');
return rdf_BlockingWrite(aStream, s);
}
nsresult
nsRDFXMLSerializer::SerializeChildAssertion(nsIOutputStream* aStream,
nsIRDFResource* aResource,
nsIRDFResource* aProperty,
nsIRDFNode* aValue)
{
nsCString qname;
nsresult rv = GetQName(aProperty, qname);
NS_ENSURE_SUCCESS(rv, rv);
rv = rdf_BlockingWrite(aStream, " <", 5);
if (NS_FAILED(rv)) return rv;
rv = rdf_BlockingWrite(aStream, qname);
if (NS_FAILED(rv)) return rv;
nsCOMPtr<nsIRDFResource> resource;
nsCOMPtr<nsIRDFLiteral> literal;
nsCOMPtr<nsIRDFInt> number;
nsCOMPtr<nsIRDFDate> date;
if ((resource = do_QueryInterface(aValue)) != nsnull) {
nsCAutoString uri;
resource->GetValueUTF8(uri);
rdf_MakeRelativeRef(mBaseURLSpec, uri);
rdf_EscapeAttributeValue(uri);
rv = rdf_BlockingWrite(aStream, kRDFResource1,
sizeof(kRDFResource1) - 1);
if (NS_FAILED(rv)) return rv;
rv = rdf_BlockingWrite(aStream, uri);
if (NS_FAILED(rv)) return rv;
rv = rdf_BlockingWrite(aStream, kRDFResource2,
sizeof(kRDFResource2) - 1);
if (NS_FAILED(rv)) return rv;
goto no_close_tag;
}
else if ((literal = do_QueryInterface(aValue)) != nsnull) {
const PRUnichar *value;
literal->GetValueConst(&value);
NS_ConvertUTF16toUTF8 s(value);
rdf_EscapeAmpersandsAndAngleBrackets(s);
rv = rdf_BlockingWrite(aStream, ">", 1);
if (NS_FAILED(rv)) return rv;
rv = rdf_BlockingWrite(aStream, s);
if (NS_FAILED(rv)) return rv;
}
else if ((number = do_QueryInterface(aValue)) != nsnull) {
PRInt32 value;
number->GetValue(&value);
nsCAutoString n;
n.AppendInt(value);
rv = rdf_BlockingWrite(aStream, kRDFParseTypeInteger,
sizeof(kRDFParseTypeInteger) - 1);
if (NS_FAILED(rv)) return rv;
rv = rdf_BlockingWrite(aStream, n);
if (NS_FAILED(rv)) return rv;
}
else if ((date = do_QueryInterface(aValue)) != nsnull) {
PRTime value;
date->GetValue(&value);
nsCAutoString s;
rdf_FormatDate(value, s);
rv = rdf_BlockingWrite(aStream, kRDFParseTypeDate,
sizeof(kRDFParseTypeDate) - 1);
if (NS_FAILED(rv)) return rv;
rv = rdf_BlockingWrite(aStream, s);
if (NS_FAILED(rv)) return rv;
}
else {
// XXX it doesn't support nsIRDFResource _or_ nsIRDFLiteral???
// We should serialize nsIRDFInt, nsIRDFDate, etc...
NS_WARNING("unknown RDF node type");
rv = rdf_BlockingWrite(aStream, kRDFUnknown, sizeof(kRDFUnknown) - 1);
if (NS_FAILED(rv)) return rv;
}
rv = rdf_BlockingWrite(aStream, "</", 2);
if (NS_FAILED(rv)) return rv;
rv = rdf_BlockingWrite(aStream, qname);
if (NS_FAILED(rv)) return rv;
return rdf_BlockingWrite(aStream, ">\n", 2);
no_close_tag:
return NS_OK;
}
nsresult
nsRDFXMLSerializer::SerializeProperty(nsIOutputStream* aStream,
nsIRDFResource* aResource,
nsIRDFResource* aProperty,
PRBool aInline,
PRInt32* aSkipped)
{
nsresult rv = NS_OK;
PRInt32 skipped = 0;
nsCOMPtr<nsISimpleEnumerator> assertions;
mDataSource->GetTargets(aResource, aProperty, PR_TRUE, getter_AddRefs(assertions));
if (! assertions)
return NS_ERROR_FAILURE;
// Serializing the assertion inline is ok as long as the property has
// only one target value, and it is a literal that doesn't include line
// breaks.
PRBool needsChild = PR_FALSE;
while (1) {
PRBool hasMore = PR_FALSE;
assertions->HasMoreElements(&hasMore);
if (! hasMore)
break;
nsCOMPtr<nsISupports> isupports;
assertions->GetNext(getter_AddRefs(isupports));
nsCOMPtr<nsIRDFLiteral> literal = do_QueryInterface(isupports);
needsChild |= (!literal);
if (!needsChild) {
assertions->HasMoreElements(&needsChild);
if (!needsChild) {
const PRUnichar* literalVal = nsnull;
literal->GetValueConst(&literalVal);
if (literalVal) {
for (; *literalVal; literalVal++) {
if (*literalVal == PRUnichar('\n') ||
*literalVal == PRUnichar('\r')) {
needsChild = PR_TRUE;
break;
}
}
}
}
}
if (aInline && !needsChild) {
rv = SerializeInlineAssertion(aStream, aResource, aProperty, literal);
}
else if (!aInline && needsChild) {
nsCOMPtr<nsIRDFNode> value = do_QueryInterface(isupports);
rv = SerializeChildAssertion(aStream, aResource, aProperty, value);
}
else {
++skipped;
rv = NS_OK;
}
if (NS_FAILED(rv))
break;
}
*aSkipped += skipped;
return rv;
}
nsresult
nsRDFXMLSerializer::SerializeDescription(nsIOutputStream* aStream,
nsIRDFResource* aResource)
{
nsresult rv;
PRBool isTypedNode = PR_FALSE;
nsCString typeQName;
nsCOMPtr<nsIRDFNode> typeNode;
mDataSource->GetTarget(aResource, kRDF_type, PR_TRUE, getter_AddRefs(typeNode));
if (typeNode) {
nsCOMPtr<nsIRDFResource> type = do_QueryInterface(typeNode, &rv);
if (type) {
// Try to get a namespace prefix. If none is available,
// just treat the description as if it weren't a typed node
// after all and emit rdf:type as a normal property. This
// seems preferable to using a bogus (invented) prefix.
isTypedNode = NS_SUCCEEDED(GetQName(type, typeQName));
}
}
nsCAutoString uri;
rv = aResource->GetValueUTF8(uri);
if (NS_FAILED(rv)) return rv;
rdf_MakeRelativeRef(mBaseURLSpec, uri);
rdf_EscapeAttributeValue(uri);
// Emit an open tag and the subject
if (isTypedNode) {
rv = rdf_BlockingWrite(aStream, NS_LITERAL_STRING(" <"));
if (NS_FAILED(rv)) return rv;
// Watch out for the default namespace!
rv = rdf_BlockingWrite(aStream, typeQName);
if (NS_FAILED(rv)) return rv;
}
else {
rv = rdf_BlockingWrite(aStream, kRDFDescriptionOpen,
sizeof(kRDFDescriptionOpen) - 1);
if (NS_FAILED(rv)) return rv;
}
if (uri[0] == PRUnichar('#')) {
uri.Cut(0, 1);
rv = rdf_BlockingWrite(aStream, kIDAttr, sizeof(kIDAttr) - 1);
}
else {
rv = rdf_BlockingWrite(aStream, kAboutAttr, sizeof(kAboutAttr) - 1);
}
if (NS_FAILED(rv)) return rv;
uri.Append('"');
rv = rdf_BlockingWrite(aStream, uri);
if (NS_FAILED(rv)) return rv;
// Any value that's a literal we can write out as an inline
// attribute on the RDF:Description
nsAutoTArray<nsIRDFResource*, 8> visited;
PRInt32 skipped = 0;
nsCOMPtr<nsISimpleEnumerator> arcs;
mDataSource->ArcLabelsOut(aResource, getter_AddRefs(arcs));
if (arcs) {
// Don't re-serialize rdf:type later on
if (isTypedNode)
visited.AppendElement(kRDF_type);
while (1) {
PRBool hasMore = PR_FALSE;
arcs->HasMoreElements(&hasMore);
if (! hasMore)
break;
nsCOMPtr<nsISupports> isupports;
arcs->GetNext(getter_AddRefs(isupports));
nsCOMPtr<nsIRDFResource> property = do_QueryInterface(isupports);
if (! property)
continue;
// Ignore properties that pertain to containers; we may be
// called from SerializeContainer() if the container resource
// has been assigned non-container properties.
if (IsContainerProperty(property))
continue;
// Only serialize values for the property once.
if (visited.Contains(property.get()))
continue;
visited.AppendElement(property.get());
SerializeProperty(aStream, aResource, property, PR_TRUE, &skipped);
}
}
if (skipped) {
// Close the RDF:Description tag.
rv = rdf_BlockingWrite(aStream, NS_LITERAL_CSTRING(">\n"));
if (NS_FAILED(rv)) return rv;
// Now write out resources (which might have their own
// substructure) as children.
mDataSource->ArcLabelsOut(aResource, getter_AddRefs(arcs));
if (arcs) {
// Forget that we've visited anything
visited.Clear();
// ... except for rdf:type
if (isTypedNode)
visited.AppendElement(kRDF_type);
while (1) {
PRBool hasMore = PR_FALSE;
arcs->HasMoreElements(&hasMore);
if (! hasMore)
break;
nsCOMPtr<nsISupports> isupports;
arcs->GetNext(getter_AddRefs(isupports));
nsCOMPtr<nsIRDFResource> property = do_QueryInterface(isupports);
if (! property)
continue;
// Ignore properties that pertain to containers; we may be
// called from SerializeContainer() if the container
// resource has been assigned non-container properties.
if (IsContainerProperty(property))
continue;
// have we already seen this property? If so, don't write it
// out again; serialize property will write each instance.
if (visited.Contains(property.get()))
continue;
visited.AppendElement(property.get());
SerializeProperty(aStream, aResource, property, PR_FALSE, &skipped);
}
}
// Emit a proper close-tag.
if (isTypedNode) {
rv = rdf_BlockingWrite(aStream, NS_LITERAL_CSTRING(" </"));
if (NS_FAILED(rv)) return rv;
// Watch out for the default namespace!
rdf_BlockingWrite(aStream, typeQName);
if (NS_FAILED(rv)) return rv;
rdf_BlockingWrite(aStream, ">\n", 2);
if (NS_FAILED(rv)) return rv;
}
else {
rv = rdf_BlockingWrite(aStream, kRDFDescriptionClose,
sizeof(kRDFDescriptionClose) - 1);
if (NS_FAILED(rv)) return rv;
}
}
else {
// If we saw _no_ child properties, then we can don't need a
// close-tag.
rv = rdf_BlockingWrite(aStream, NS_LITERAL_CSTRING(" />\n"));
if (NS_FAILED(rv)) return rv;
}
return NS_OK;
}
nsresult
nsRDFXMLSerializer::SerializeMember(nsIOutputStream* aStream,
nsIRDFResource* aContainer,
nsIRDFNode* aMember)
{
// If it's a resource, then output a "<RDF:li RDF:resource=... />"
// tag, because we'll be dumping the resource separately. (We
// iterate thru all the resources in the datasource,
// remember?) Otherwise, output the literal value.
nsCOMPtr<nsIRDFResource> resource;
nsCOMPtr<nsIRDFLiteral> literal;
nsCOMPtr<nsIRDFInt> number;
nsCOMPtr<nsIRDFDate> date;
static const char kRDFLIOpen[] = " <RDF:li";
nsresult rv = rdf_BlockingWrite(aStream, kRDFLIOpen,
sizeof(kRDFLIOpen) - 1);
if (NS_FAILED(rv)) return rv;
if ((resource = do_QueryInterface(aMember)) != nsnull) {
nsCAutoString uri;
resource->GetValueUTF8(uri);
rdf_MakeRelativeRef(mBaseURLSpec, uri);
rdf_EscapeAttributeValue(uri);
rv = rdf_BlockingWrite(aStream, kRDFResource1,
sizeof(kRDFResource1) - 1);
if (NS_FAILED(rv)) return rv;
rv = rdf_BlockingWrite(aStream, uri);
if (NS_FAILED(rv)) return rv;
rv = rdf_BlockingWrite(aStream, kRDFResource2,
sizeof(kRDFResource2) - 1);
if (NS_FAILED(rv)) return rv;
goto no_close_tag;
}
else if ((literal = do_QueryInterface(aMember)) != nsnull) {
const PRUnichar *value;
literal->GetValueConst(&value);
static const char kRDFLIOpenGT[] = ">";
// close the '<RDF:LI' before adding the literal
rv = rdf_BlockingWrite(aStream, kRDFLIOpenGT,
sizeof(kRDFLIOpenGT) - 1);
if (NS_FAILED(rv)) return rv;
NS_ConvertUTF16toUTF8 s(value);
rdf_EscapeAmpersandsAndAngleBrackets(s);
rv = rdf_BlockingWrite(aStream, s);
if (NS_FAILED(rv)) return rv;
}
else if ((number = do_QueryInterface(aMember)) != nsnull) {
PRInt32 value;
number->GetValue(&value);
nsCAutoString n;
n.AppendInt(value);
rv = rdf_BlockingWrite(aStream, kRDFParseTypeInteger,
sizeof(kRDFParseTypeInteger) - 1);
if (NS_FAILED(rv)) return rv;
rv = rdf_BlockingWrite(aStream, n);
if (NS_FAILED(rv)) return rv;
}
else if ((date = do_QueryInterface(aMember)) != nsnull) {
PRTime value;
date->GetValue(&value);
nsCAutoString s;
rdf_FormatDate(value, s);
rv = rdf_BlockingWrite(aStream, kRDFParseTypeDate,
sizeof(kRDFParseTypeDate) - 1);
if (NS_FAILED(rv)) return rv;
rv = rdf_BlockingWrite(aStream, s);
if (NS_FAILED(rv)) return rv;
}
else {
// XXX it doesn't support nsIRDFResource _or_ nsIRDFLiteral???
// We should serialize nsIRDFInt, nsIRDFDate, etc...
NS_WARNING("unknown RDF node type");
rv = rdf_BlockingWrite(aStream, kRDFUnknown, sizeof(kRDFUnknown) - 1);
if (NS_FAILED(rv)) return rv;
}
{
static const char kRDFLIClose[] = "</RDF:li>\n";
rv = rdf_BlockingWrite(aStream, kRDFLIClose, sizeof(kRDFLIClose) - 1);
if (NS_FAILED(rv)) return rv;
}
no_close_tag:
return NS_OK;
}
nsresult
nsRDFXMLSerializer::SerializeContainer(nsIOutputStream* aStream,
nsIRDFResource* aContainer)
{
nsresult rv;
nsCAutoString tag;
// Decide if it's a sequence, bag, or alternation, and print the
// appropriate tag-open sequence
if (IsA(mDataSource, aContainer, kRDF_Bag)) {
tag.AssignLiteral("RDF:Bag");
}
else if (IsA(mDataSource, aContainer, kRDF_Seq)) {
tag.AssignLiteral("RDF:Seq");
}
else if (IsA(mDataSource, aContainer, kRDF_Alt)) {
tag.AssignLiteral("RDF:Alt");
}
else {
NS_ASSERTION(PR_FALSE, "huh? this is _not_ a container.");
return NS_ERROR_UNEXPECTED;
}
rv = rdf_BlockingWrite(aStream, " <", 3);
if (NS_FAILED(rv)) return rv;
rv = rdf_BlockingWrite(aStream, tag);
if (NS_FAILED(rv)) return rv;
// Unfortunately, we always need to print out the identity of the
// resource, even if was constructed "anonymously". We need to do
// this because we never really know who else might be referring
// to it...
nsCAutoString uri;
if (NS_SUCCEEDED(aContainer->GetValueUTF8(uri))) {
rdf_MakeRelativeRef(mBaseURLSpec, uri);
rdf_EscapeAttributeValue(uri);
if (uri.First() == '#') {
// Okay, it's actually identified as an element in the
// current document, not trying to decorate some absolute
// URI. We can use the 'ID=' attribute...
uri.Cut(0, 1); // chop the '#'
rv = rdf_BlockingWrite(aStream, kIDAttr, sizeof(kIDAttr) - 1);
if (NS_FAILED(rv)) return rv;
}
else {
// We need to cheat and spit out an illegal 'about=' on
// the sequence.
rv = rdf_BlockingWrite(aStream, kAboutAttr,
sizeof(kAboutAttr) - 1);
if (NS_FAILED(rv)) return rv;
}
rv = rdf_BlockingWrite(aStream, uri);
if (NS_FAILED(rv)) return rv;
rv = rdf_BlockingWrite(aStream, "\"", 1);
if (NS_FAILED(rv)) return rv;
}
rv = rdf_BlockingWrite(aStream, ">\n", 2);
if (NS_FAILED(rv)) return rv;
// First iterate through each of the ordinal elements (the RDF/XML
// syntax doesn't allow us to place properties on RDF container
// elements).
nsCOMPtr<nsISimpleEnumerator> elements;
rv = NS_NewContainerEnumerator(mDataSource, aContainer, getter_AddRefs(elements));
if (NS_SUCCEEDED(rv)) {
while (1) {
PRBool hasMore;
rv = elements->HasMoreElements(&hasMore);
if (NS_FAILED(rv)) break;
if (! hasMore)
break;
nsCOMPtr<nsISupports> isupports;
elements->GetNext(getter_AddRefs(isupports));
nsCOMPtr<nsIRDFNode> element = do_QueryInterface(isupports);
NS_ASSERTION(element != nsnull, "not an nsIRDFNode");
if (! element)
continue;
SerializeMember(aStream, aContainer, element);
}
}
// close the container tag
rv = rdf_BlockingWrite(aStream, " </", 4);
if (NS_FAILED(rv)) return rv;
tag.Append(">\n", 2);
rv = rdf_BlockingWrite(aStream, tag);
if (NS_FAILED(rv)) return rv;
// Now, we iterate through _all_ of the arcs, in case someone has
// applied properties to the bag itself. These'll be placed in a
// separate RDF:Description element.
nsCOMPtr<nsISimpleEnumerator> arcs;
mDataSource->ArcLabelsOut(aContainer, getter_AddRefs(arcs));
PRBool wroteDescription = PR_FALSE;
while (! wroteDescription) {
PRBool hasMore = PR_FALSE;
rv = arcs->HasMoreElements(&hasMore);
if (NS_FAILED(rv)) break;
if (! hasMore)
break;
nsIRDFResource* property;
rv = arcs->GetNext((nsISupports**) &property);
if (NS_FAILED(rv)) break;
// If it's a membership property, then output a "LI"
// tag. Otherwise, output a property.
if (! IsContainerProperty(property)) {
rv = SerializeDescription(aStream, aContainer);
wroteDescription = PR_TRUE;
}
NS_RELEASE(property);
if (NS_FAILED(rv))
break;
}
return NS_OK;
}
nsresult
nsRDFXMLSerializer::SerializePrologue(nsIOutputStream* aStream)
{
static const char kXMLVersion[] = "<?xml version=\"1.0\"?>\n";
nsresult rv;
rv = rdf_BlockingWrite(aStream, kXMLVersion, sizeof(kXMLVersion) - 1);
if (NS_FAILED(rv)) return rv;
// global name space declarations
rv = rdf_BlockingWrite(aStream, NS_LITERAL_CSTRING("<RDF:RDF "));