XMLStreamWriterImpl.java 27.1 KB
Newer Older
1
/* XMLStreamWriterImpl.java --
Tom Tromey committed
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
   Copyright (C) 2005  Free Software Foundation, Inc.

This file is part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

GNU Classpath 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
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */

package gnu.xml.stream;

import java.io.IOException;
import java.io.Writer;
42 43
import java.util.Enumeration;
import java.util.HashSet;
Tom Tromey committed
44
import java.util.LinkedList;
45
import java.util.Set;
Tom Tromey committed
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62

import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

import org.xml.sax.helpers.NamespaceSupport;

/**
 * Simple XML stream writer.
 *
 * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a>
 */
public class XMLStreamWriterImpl
  implements XMLStreamWriter
{

63 64 65
  /**
   * The underlying character stream to write to.
   */
Tom Tromey committed
66
  protected final Writer writer;
67 68 69 70 71

  /**
   * The encoding being used.
   * Note that this must match the encoding of the character stream.
   */
Tom Tromey committed
72
  protected final String encoding;
73 74 75 76 77 78 79

  /**
   * Whether prefix defaulting is being used.
   * If true and a prefix has not been defined for a namespace specified on
   * an element or an attribute, a new prefix and namespace declaration will
   * be created.
   */
Tom Tromey committed
80
  protected final boolean prefixDefaulting;
81 82 83 84 85

  /**
   * The namespace context used to determine the namespace-prefix mappings
   * in scope.
   */
Tom Tromey committed
86
  protected NamespaceContext namespaceContext;
87

88 89 90 91
  /**
   * The stack of elements in scope.
   * Used to close the remaining elements.
   */
Tom Tromey committed
92
  private LinkedList elements;
93 94 95 96

  /**
   * Whether a start element has been opened but not yet closed.
   */
Tom Tromey committed
97
  private boolean inStartElement;
98 99 100 101

  /**
   * Whether we are in an empty element.
   */
Tom Tromey committed
102
  private boolean emptyElement;
103

Tom Tromey committed
104
  private NamespaceSupport namespaces;
105 106
  private int count = 0;

107 108 109
  private boolean xml11;
  private boolean hasXML11RestrictedChars;

110 111 112 113 114 115
  /**
   * Constructor.
   * @see #writer
   * @see #encoding
   * @see #prefixDefaulting
   */
Tom Tromey committed
116 117 118 119 120 121 122 123 124 125
  protected XMLStreamWriterImpl(Writer writer, String encoding,
                                boolean prefixDefaulting)
  {
    this.writer = writer;
    this.encoding = encoding;
    this.prefixDefaulting = prefixDefaulting;
    elements = new LinkedList();
    namespaces = new NamespaceSupport();
  }

126 127 128 129
  /**
   * Write the end of a start-element event.
   * This will close the element if it was defined to be an empty element.
   */
Tom Tromey committed
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
  private void endStartElement()
    throws IOException
  {
    if (!inStartElement)
      return;
    if (emptyElement)
      {
        writer.write('/');
        elements.removeLast();
        namespaces.popContext();
        emptyElement = false;
      }
    writer.write('>');
    inStartElement = false;
  }

  public void writeStartElement(String localName)
    throws XMLStreamException
  {
    try
      {
151 152 153
        if (!isName(localName))
          throw new IllegalArgumentException("illegal Name: " + localName);

Tom Tromey committed
154 155
        endStartElement();
        namespaces.pushContext();
156

Tom Tromey committed
157 158
        writer.write('<');
        writer.write(localName);
159

Tom Tromey committed
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
        elements.addLast(new String[] { null, localName });
        inStartElement = true;
      }
    catch (IOException e)
      {
        XMLStreamException e2 = new XMLStreamException(e);
        e2.initCause(e);
        throw e2;
      }
  }

  public void writeStartElement(String namespaceURI, String localName)
    throws XMLStreamException
  {
    try
      {
176 177 178 179 180
        if (namespaceURI != null && !isURI(namespaceURI))
          throw new IllegalArgumentException("illegal URI: " + namespaceURI);
        if (!isName(localName))
          throw new IllegalArgumentException("illegal Name: " + localName);

Tom Tromey committed
181 182
        endStartElement();
        namespaces.pushContext();
183

Tom Tromey committed
184 185 186 187 188
        String prefix = getPrefix(namespaceURI);
        boolean isDeclared = (prefix != null);
        if (!isDeclared)
          {
            if (prefixDefaulting)
189
              prefix = createPrefix(namespaceURI);
Tom Tromey committed
190 191 192 193 194 195 196 197 198 199 200
            else
              throw new XMLStreamException("namespace " + namespaceURI +
                                           " has not been declared");
          }
        writer.write('<');
        if (!"".equals(prefix))
          {
            writer.write(prefix);
            writer.write(':');
          }
        writer.write(localName);
201 202
        inStartElement = true;
        if (!isDeclared)
Tom Tromey committed
203
          {
204
            writeNamespaceImpl(prefix, namespaceURI);
Tom Tromey committed
205
          }
206

Tom Tromey committed
207 208 209 210 211 212 213 214 215 216
        elements.addLast(new String[] { prefix, localName });
      }
    catch (IOException e)
      {
        XMLStreamException e2 = new XMLStreamException(e);
        e2.initCause(e);
        throw e2;
      }
  }

217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
  /**
   * Creates a new unique prefix in the document.
   * Subclasses may override this method to provide a suitably unique prefix
   * for the given namespace.
   * @param namespaceURI the namespace URI
   */
  protected String createPrefix(String namespaceURI)
  {
    Set prefixes = new HashSet();
    for (Enumeration e = namespaces.getPrefixes(); e.hasMoreElements(); )
      prefixes.add(e.nextElement());
    String ret;
    do
      {
        ret = "ns" + (count++);
      }
    while (prefixes.contains(ret));
    return ret;
  }

Tom Tromey committed
237 238 239 240 241 242
  public void writeStartElement(String prefix, String localName,
                                String namespaceURI)
    throws XMLStreamException
  {
    try
      {
243 244
        if (namespaceURI != null && !isURI(namespaceURI))
          throw new IllegalArgumentException("illegal URI: " + namespaceURI);
245
        if (prefix != null && !isPrefix(prefix))
246 247 248 249
          throw new IllegalArgumentException("illegal NCName: " + prefix);
        if (!isNCName(localName))
          throw new IllegalArgumentException("illegal NCName: " + localName);

Tom Tromey committed
250 251
        endStartElement();
        namespaces.pushContext();
252

Tom Tromey committed
253 254 255 256 257 258 259 260 261 262 263
        String currentPrefix = getPrefix(namespaceURI);
        boolean isCurrent = prefix.equals(currentPrefix);
        writer.write('<');
        if (!"".equals(prefix))
          {
            writer.write(prefix);
            writer.write(':');
          }
        writer.write(localName);
        if (prefixDefaulting && !isCurrent)
          {
264
            writeNamespaceImpl(prefix, namespaceURI);
Tom Tromey committed
265
          }
266

Tom Tromey committed
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
        elements.addLast(new String[] { prefix, localName });
        inStartElement = true;
      }
    catch (IOException e)
      {
        XMLStreamException e2 = new XMLStreamException(e);
        e2.initCause(e);
        throw e2;
      }
  }

  public void writeEmptyElement(String namespaceURI, String localName)
    throws XMLStreamException
  {
    writeStartElement(namespaceURI, localName);
    emptyElement = true;
  }

  public void writeEmptyElement(String prefix, String localName,
                                String namespaceURI)
    throws XMLStreamException
  {
    writeStartElement(prefix, localName, namespaceURI);
    emptyElement = true;
  }

  public void writeEmptyElement(String localName)
    throws XMLStreamException
  {
    writeStartElement(localName);
    emptyElement = true;
  }

  public void writeEndElement()
    throws XMLStreamException
  {
303 304
    if (elements.isEmpty())
      throw new IllegalStateException("no matching start element");
Tom Tromey committed
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
    try
      {
        endStartElement();
        String[] element = (String[]) elements.removeLast();
        namespaces.popContext();

        writer.write('<');
        writer.write('/');
        if (element[0] != null && !"".equals(element[0]))
          {
            writer.write(element[0]);
            writer.write(':');
          }
        writer.write(element[1]);
        writer.write('>');
      }
    catch (IOException e)
      {
        XMLStreamException e2 = new XMLStreamException(e);
        e2.initCause(e);
        throw e2;
      }
  }

  public void writeEndDocument()
    throws XMLStreamException
  {
    while (!elements.isEmpty())
      writeEndElement();
  }

  public void close()
    throws XMLStreamException
  {
    flush();
  }

  public void flush()
    throws XMLStreamException
  {
    try
      {
        writer.flush();
      }
    catch (IOException e)
      {
        XMLStreamException e2 = new XMLStreamException(e);
        e2.initCause(e);
        throw e2;
      }
  }

  public void writeAttribute(String localName, String value)
    throws XMLStreamException
  {
    if (!inStartElement)
      throw new IllegalStateException();
    try
      {
364 365 366 367 368
        if (!isName(localName))
          throw new IllegalArgumentException("illegal Name: " + localName);
        if (!isChars(value))
          throw new IllegalArgumentException("illegal character: " + value);

Tom Tromey committed
369 370 371 372
        writer.write(' ');
        writer.write(localName);
        writer.write('=');
        writer.write('"');
373 374 375 376
        if (hasXML11RestrictedChars)
          writeEncodedWithRestrictedChars(value, true);
        else
          writeEncoded(value, true);
Tom Tromey committed
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
        writer.write('"');
      }
    catch (IOException e)
      {
        XMLStreamException e2 = new XMLStreamException(e);
        e2.initCause(e);
        throw e2;
      }
  }

  public void writeAttribute(String prefix, String namespaceURI,
                             String localName, String value)
    throws XMLStreamException
  {
    if (!inStartElement)
      throw new IllegalStateException();
    try
      {
395 396
        if (namespaceURI != null && !isURI(namespaceURI))
          throw new IllegalArgumentException("illegal URI: " + namespaceURI);
397
        if (prefix != null && !isPrefix(prefix))
398 399 400 401 402 403
          throw new IllegalArgumentException("illegal NCName: " + prefix);
        if (!isNCName(localName))
          throw new IllegalArgumentException("illegal NCName: " + localName);
        if (!isChars(value))
          throw new IllegalArgumentException("illegal character: " + value);

Tom Tromey committed
404 405 406 407
        String currentPrefix = getPrefix(namespaceURI);
        if (currentPrefix == null)
          {
            if (prefixDefaulting)
408
              writeNamespaceImpl(prefix, namespaceURI);
Tom Tromey committed
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
            else
              throw new XMLStreamException("namespace " + namespaceURI +
                                           " is not bound");
          }
        else if (!currentPrefix.equals(prefix))
          throw new XMLStreamException("namespace " + namespaceURI +
                                       " is bound to prefix " +
                                       currentPrefix);
        writer.write(' ');
        if (!"".equals(prefix))
          {
            writer.write(prefix);
            writer.write(':');
          }
        writer.write(localName);
        writer.write('=');
        writer.write('"');
426 427 428 429
        if (hasXML11RestrictedChars)
          writeEncodedWithRestrictedChars(value, true);
        else
          writeEncoded(value, true);
Tom Tromey committed
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
        writer.write('"');
      }
    catch (IOException e)
      {
        XMLStreamException e2 = new XMLStreamException(e);
        e2.initCause(e);
        throw e2;
      }
  }

  public void writeAttribute(String namespaceURI, String localName,
                             String value)
    throws XMLStreamException
  {
    if (!inStartElement)
      throw new IllegalStateException();
    try
      {
448 449 450 451 452 453
        if (namespaceURI != null && !isURI(namespaceURI))
          throw new IllegalArgumentException("illegal URI: " + namespaceURI);
        if (!isName(localName))
          throw new IllegalArgumentException("illegal Name: " + localName);
        if (!isChars(value))
          throw new IllegalArgumentException("illegal character: " + value);
454

Tom Tromey committed
455 456 457 458 459 460
        String prefix = getPrefix(namespaceURI);
        if (prefix == null)
          {
            if (prefixDefaulting)
              {
                prefix = XMLConstants.DEFAULT_NS_PREFIX;
461
                writeNamespaceImpl(prefix, namespaceURI);
Tom Tromey committed
462 463 464 465 466 467 468 469 470 471 472 473 474 475
              }
            else
              throw new XMLStreamException("namespace " + namespaceURI +
                                           " is not bound");
          }
        writer.write(' ');
        if (!"".equals(prefix))
          {
            writer.write(prefix);
            writer.write(':');
          }
        writer.write(localName);
        writer.write('=');
        writer.write('"');
476 477 478 479
        if (hasXML11RestrictedChars)
          writeEncodedWithRestrictedChars(value, true);
        else
          writeEncoded(value, true);
Tom Tromey committed
480 481 482 483 484 485 486 487 488 489 490 491 492
        writer.write('"');
      }
    catch (IOException e)
      {
        XMLStreamException e2 = new XMLStreamException(e);
        e2.initCause(e);
        throw e2;
      }
  }

  public void writeNamespace(String prefix, String namespaceURI)
    throws XMLStreamException
  {
493 494 495 496 497
    if (prefix == null || "".equals(prefix) || "xmlns".equals(prefix))
    {
      writeDefaultNamespace(namespaceURI);
      return;
    }
Tom Tromey committed
498 499 500 501
    if (!inStartElement)
      throw new IllegalStateException();
    try
      {
502 503
        if (!isURI(namespaceURI))
          throw new IllegalArgumentException("illegal URI: " + namespaceURI);
504
        if (!isPrefix(prefix))
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
          throw new IllegalArgumentException("illegal NCName: " + prefix);
      }
    catch (IOException e)
      {
        XMLStreamException e2 = new XMLStreamException(e);
        e2.initCause(e);
        throw e2;
      }
    writeNamespaceImpl(prefix, namespaceURI);
  }

  private void writeNamespaceImpl(String prefix, String namespaceURI)
    throws XMLStreamException
  {
    try
      {
Tom Tromey committed
521 522 523 524
        if (prefix == null)
          prefix = XMLConstants.DEFAULT_NS_PREFIX;

        setPrefix(prefix, namespaceURI);
525

Tom Tromey committed
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
        writer.write(' ');
        writer.write("xmlns");
        if (!XMLConstants.DEFAULT_NS_PREFIX.equals(prefix))
          {
            writer.write(':');
            writer.write(prefix);
          }
        writer.write('=');
        writer.write('"');
        writer.write(namespaceURI);
        writer.write('"');
      }
    catch (IOException e)
      {
        XMLStreamException e2 = new XMLStreamException(e);
        e2.initCause(e);
        throw e2;
      }
  }

  public void writeDefaultNamespace(String namespaceURI)
    throws XMLStreamException
  {
549 550 551 552 553
    if (!inStartElement)
      throw new IllegalStateException();
    if (!isURI(namespaceURI))
      throw new IllegalArgumentException("illegal URI: " + namespaceURI);
    writeNamespaceImpl(XMLConstants.DEFAULT_NS_PREFIX, namespaceURI);
Tom Tromey committed
554 555 556 557 558
  }

  public void writeComment(String data)
    throws XMLStreamException
  {
559 560
    if (data == null)
      return;
Tom Tromey committed
561 562
    try
      {
563 564 565 566 567
        if (!isChars(data))
          throw new IllegalArgumentException("illegal XML character: " + data);
        if (data.indexOf("--") != -1)
          throw new IllegalArgumentException("illegal comment: " + data);

Tom Tromey committed
568
        endStartElement();
569

Tom Tromey committed
570
        writer.write("<!--");
571 572 573 574 575 576 577 578 579 580 581 582 583
        if (hasXML11RestrictedChars)
          {
            int[] seq = UnicodeReader.toCodePointArray(data);
            for (int i = 0; i < seq.length; i++)
              {
                int c = seq[i];
                if (XMLParser.isXML11RestrictedChar(c))
                  writer.write("&#x" + Integer.toHexString(c) + ";");
                else
                  writer.write(Character.toChars(i));
              }
          }
        else
Tom Tromey committed
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
          writer.write(data);
        writer.write("-->");
      }
    catch (IOException e)
      {
        XMLStreamException e2 = new XMLStreamException(e);
        e2.initCause(e);
        throw e2;
      }
  }

  public void writeProcessingInstruction(String target)
    throws XMLStreamException
  {
    writeProcessingInstruction(target, null);
  }

  public void writeProcessingInstruction(String target, String data)
    throws XMLStreamException
  {
    try
      {
606 607 608 609 610
        if (!isName(target) || "xml".equalsIgnoreCase(target))
          throw new IllegalArgumentException("illegal PITarget: " + target);
        if (data != null && !isChars(data))
          throw new IllegalArgumentException("illegal XML character: " + data);

Tom Tromey committed
611 612 613 614 615 616 617 618
        endStartElement();

        writer.write('<');
        writer.write('?');
        writer.write(target);
        if (data != null)
          {
            writer.write(' ');
619 620 621 622 623 624 625 626 627 628 629 630 631 632
            if (hasXML11RestrictedChars)
              {
                int[] seq = UnicodeReader.toCodePointArray(data);
                for (int i = 0; i < seq.length; i++)
                  {
                    int c = seq[i];
                    if (XMLParser.isXML11RestrictedChar(c))
                      writer.write("&#x" + Integer.toHexString(c) + ";");
                    else
                      writer.write(Character.toChars(i));
                  }
              }
            else
              writer.write(data);
Tom Tromey committed
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
          }
        writer.write('?');
        writer.write('>');
      }
    catch (IOException e)
      {
        XMLStreamException e2 = new XMLStreamException(e);
        e2.initCause(e);
        throw e2;
      }
  }

  public void writeCData(String data)
    throws XMLStreamException
  {
    try
      {
650 651
        if (!isChars(data) || hasXML11RestrictedChars)
          throw new IllegalArgumentException("illegal XML character: " + data);
Tom Tromey committed
652
        if (data.indexOf("]]") != -1)
653
          throw new IllegalArgumentException("illegal CDATA section: " + data);
654

655
        endStartElement();
Tom Tromey committed
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673

        writer.write("<![CDATA[");
        writer.write(data);
        writer.write("]]>");
      }
    catch (IOException e)
      {
        XMLStreamException e2 = new XMLStreamException(e);
        e2.initCause(e);
        throw e2;
      }
  }

  public void writeDTD(String dtd)
    throws XMLStreamException
  {
    try
      {
674 675
        // XXX: Should we parse the doctypedecl at this point to ensure
        // wellformedness?
Tom Tromey committed
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
        writer.write("<!DOCTYPE ");
        writer.write(dtd);
        writer.write('>');
      }
    catch (IOException e)
      {
        XMLStreamException e2 = new XMLStreamException(e);
        e2.initCause(e);
        throw e2;
      }
  }

  public void writeEntityRef(String name)
    throws XMLStreamException
  {
    try
      {
693 694 695
        if (!isName(name))
          throw new IllegalArgumentException("illegal Name: " + name);

Tom Tromey committed
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
        endStartElement();

        writer.write('&');
        writer.write(name);
        writer.write(';');
      }
    catch (IOException e)
      {
        XMLStreamException e2 = new XMLStreamException(e);
        e2.initCause(e);
        throw e2;
      }
  }

  public void writeStartDocument()
    throws XMLStreamException
  {
    writeStartDocument(null, null);
  }

  public void writeStartDocument(String version)
    throws XMLStreamException
  {
    writeStartDocument(null, version);
  }

  public void writeStartDocument(String encoding, String version)
    throws XMLStreamException
  {
    if (version == null)
      version = "1.0";
727 728
    else if ("1.1".equals(version))
      xml11 = true;
Tom Tromey committed
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
    encoding = this.encoding; // YES: the parameter must be ignored
    if (encoding == null)
      encoding = "UTF-8";
    if (!"1.0".equals(version) && !"1.1".equals(version))
      throw new IllegalArgumentException(version);
    try
      {
        writer.write("<?xml version=\"");
        writer.write(version);
        writer.write("\" encoding=\"");
        writer.write(encoding);
        writer.write("\"?>");
        writer.write(System.getProperty("line.separator"));
      }
    catch (IOException e)
      {
        XMLStreamException e2 = new XMLStreamException(e);
        e2.initCause(e);
        throw e2;
      }
  }

  public void writeCharacters(String text)
    throws XMLStreamException
  {
754 755
    if (text == null)
      return;
Tom Tromey committed
756 757
    try
      {
758 759 760
        if (!isChars(text))
          throw new IllegalArgumentException("illegal XML character: " + text);

Tom Tromey committed
761 762
        endStartElement();

763 764 765
        if (hasXML11RestrictedChars)
          writeEncodedWithRestrictedChars(text, false);
        else
Tom Tromey committed
766 767 768 769 770 771 772 773 774 775 776 777 778
          writeEncoded(text, false);
      }
    catch (IOException e)
      {
        XMLStreamException e2 = new XMLStreamException(e);
        e2.initCause(e);
        throw e2;
      }
  }

  public void writeCharacters(char[] text, int start, int len)
    throws XMLStreamException
  {
779
    writeCharacters(new String(text, start, len));
Tom Tromey committed
780 781 782 783 784 785 786 787 788 789 790 791 792 793
  }

  public String getPrefix(String uri)
    throws XMLStreamException
  {
    String prefix = namespaces.getPrefix(uri);
    if (prefix == null && namespaceContext != null)
      prefix = namespaceContext.getPrefix(uri);
    return prefix;
  }

  public void setPrefix(String prefix, String uri)
    throws XMLStreamException
  {
794 795 796 797
    try
      {
        if (!isURI(uri))
          throw new IllegalArgumentException("illegal URI: " + uri);
798
        if (!isPrefix(prefix))
799 800 801 802 803 804 805 806
          throw new IllegalArgumentException("illegal NCName: " + prefix);
      }
    catch (IOException e)
      {
        XMLStreamException e2 = new XMLStreamException(e);
        e2.initCause(e);
        throw e2;
      }
Tom Tromey committed
807 808 809 810 811 812 813
    if (!namespaces.declarePrefix(prefix, uri))
      throw new XMLStreamException("illegal prefix " + prefix);
  }

  public void setDefaultNamespace(String uri)
    throws XMLStreamException
  {
814 815
    if (!isURI(uri))
      throw new IllegalArgumentException("illegal URI: " + uri);
Tom Tromey committed
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
    if (!namespaces.declarePrefix(XMLConstants.DEFAULT_NS_PREFIX, uri))
      throw new XMLStreamException("illegal default namespace prefix");
  }

  public void setNamespaceContext(NamespaceContext context)
    throws XMLStreamException
  {
    namespaceContext = context;
  }

  public NamespaceContext getNamespaceContext()
  {
    return namespaceContext;
  }

  public Object getProperty(String name)
    throws IllegalArgumentException
  {
    throw new IllegalArgumentException(name);
  }

837 838 839 840 841 842
  /**
   * Write the specified text, ensuring that the content is suitably encoded
   * for XML.
   * @param text the text to write
   * @param inAttr whether we are in an attribute value
   */
Tom Tromey committed
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
  private void writeEncoded(String text, boolean inAttr)
    throws IOException
  {
    char[] chars = text.toCharArray();
    int start = 0;
    int end = chars.length;
    int len = 0;
    for (int i = start; i < end; i++)
      {
        char c = chars[i];
        if (c == '<' || c == '>' || c == '&')
          {
            writer.write(chars, start, len);
            if (c == '<')
              writer.write("&lt;");
            else if (c == '>')
              writer.write("&gt;");
            else
              writer.write("&amp;");
            start = i + 1;
            len = 0;
          }
        else if (inAttr && (c == '"' || c == '\''))
          {
            writer.write(chars, start, len);
            if (c == '"')
              writer.write("&quot;");
            else
              writer.write("&apos;");
            start = i + 1;
            len = 0;
          }
        else
          len++;
      }
    if (len > 0)
      writer.write(chars, start, len);
  }
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

  /**
   * Writes the specified text, in the knowledge that some of the
   * characters are XML 1.1 restricted characters.
   */
  private void writeEncodedWithRestrictedChars(String text, boolean inAttr)
    throws IOException
  {
    int[] seq = UnicodeReader.toCodePointArray(text);
    for (int i = 0; i < seq.length; i++)
      {
        int c = seq[i];
        switch (c)
          {
          case 0x3c: // '<'
            writer.write("&lt;");
            break;
          case 0x3e: // '>'
            writer.write("&gt;");
            break;
          case 0x26: // '&'
            writer.write("&amp;");
            break;
          case 0x22: // '"'
            if (inAttr)
              writer.write("&quot;");
            else
              writer.write(c);
            break;
          case 0x27: // '\''
            if (inAttr)
              writer.write("&apos;");
            else
              writer.write(c);
            break;
          default:
            if (XMLParser.isXML11RestrictedChar(c))
              writer.write("&#x" + Integer.toHexString(c) + ";");
            else
              {
                char[] chars = Character.toChars(c);
                writer.write(chars, 0, chars.length);
              }
          }
      }
  }

  private boolean isName(String text)
    throws IOException
  {
    if (text == null)
      return false;
    int[] seq = UnicodeReader.toCodePointArray(text);
    if (seq.length < 1)
      return false;
    if (!XMLParser.isNameStartCharacter(seq[0], xml11))
      return false;
    for (int i = 1; i < seq.length; i++)
      {
        if (!XMLParser.isNameCharacter(seq[i], xml11))
          return false;
      }
    return true;
  }

946 947 948 949 950 951 952 953 954
  private boolean isPrefix(String text)
    throws IOException
  {
    if (XMLConstants.DEFAULT_NS_PREFIX.equals(text)) {
        return true;
    }
    return isNCName(text);
  }

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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
  private boolean isNCName(String text)
    throws IOException
  {
    if (text == null)
      return false;
    int[] seq = UnicodeReader.toCodePointArray(text);
    if (seq.length < 1)
      return false;
    if (!XMLParser.isNameStartCharacter(seq[0], xml11) || seq[0] == 0x3a)
      return false;
    for (int i = 1; i < seq.length; i++)
      {
        if (!XMLParser.isNameCharacter(seq[i], xml11) || seq[i] == 0x3a)
          return false;
      }
    return true;
  }

  private boolean isChars(String text)
    throws IOException
  {
    if (text == null)
      return false;
    int[] seq = UnicodeReader.toCodePointArray(text);
    hasXML11RestrictedChars = false;
    if (xml11)
      {
        for (int i = 0; i < seq.length; i++)
          {
            if (!XMLParser.isXML11Char(seq[i]))
              return false;
            if (XMLParser.isXML11RestrictedChar(seq[i]))
              hasXML11RestrictedChars = true;
          }
      }
    else
      {
        for (int i = 0; i < seq.length; i++)
          {
            if (!XMLParser.isChar(seq[i]))
              return false;
          }
      }
    return true;
  }

  private boolean isURI(String text)
  {
    if (text == null)
      return false;
    char[] chars = text.toCharArray();
    if (chars.length < 1)
      return false;
    for (int i = 0; i < chars.length; i++)
      {
        if (chars[i] < 0x20 || chars[i] >= 0x7f)
          return false;
      }
    return true;
  }
1015

1016
}