KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > portal > format > parser > entity > XML1_0CharacterEntityReferenceParser


1 /*****************************************
2  * *
3  * JBoss Portal: The OpenSource Portal *
4  * *
5  * Distributable under LGPL license. *
6  * See terms of license at gnu.org. *
7  * *
8  *****************************************/

9 package org.jboss.portal.format.parser.entity;
10
11 import org.jboss.portal.format.parser.AbstractParser;
12 import org.jboss.portal.format.parser.TextEvent;
13
14 import java.util.regex.Pattern JavaDoc;
15 import java.util.regex.Matcher JavaDoc;
16
17 /**
18  * Detect XML 1.0 character entity references.
19  *
20  * @author <a HREF="mailto:julien@jboss.org">Julien Viet</a>
21  * @version $Revision: 1.3 $
22  */

23 public class XML1_0CharacterEntityReferenceParser extends AbstractParser
24 {
25
26    private final TextEvent textEvent = new TextEvent();
27    private final CharacterEntityReferenceEvent cere = new CharacterEntityReferenceEvent();
28
29    private static Pattern JavaDoc pattern = Pattern.compile("&#(?:(?:x[0-9a-fA-F]{1,4})|(?:[0-9]{1,5}));");
30
31    public void parse(char[] chars, int offset, int length)
32    {
33       CharSequence JavaDoc seq = new CharSequenceImpl(chars, offset, length);
34       Matcher JavaDoc matcher = pattern.matcher(seq);
35       int from = offset;
36       while (matcher.find())
37       {
38          int to = matcher.start();
39          textEvent.setText(chars, from, to - from);
40          handler.handle(textEvent);
41          from = matcher.end();
42          cere.setText(chars, to, from - to);
43          handler.handle(cere);
44       }
45       if (from < offset + length)
46       {
47          textEvent.setText(chars, from, offset + length - from);
48          handler.handle(textEvent);
49       }
50    }
51
52    private static class CharSequenceImpl implements CharSequence JavaDoc
53    {
54       private final char[] chars;
55       private final int offset;
56       private final int length;
57       public CharSequenceImpl(char[] chars, int offset, int length)
58       {
59          this.chars = chars;
60          this.offset = offset;
61          this.length = length;
62       }
63       public int length()
64       {
65          return length;
66       }
67       public char charAt(int index)
68       {
69          return chars[offset + index];
70       }
71       public CharSequence JavaDoc subSequence(int start, int end)
72       {
73          return new CharSequenceImpl(chars, start, end - start);
74       }
75    }
76 }
77
Popular Tags