Changeset 3321 in josm


Ignore:
Timestamp:
2010-06-08T21:56:38+02:00 (14 years ago)
Author:
jttt
Message:

Validate tagging presets when they're added in Preferences dialog

Location:
trunk
Files:
1 added
10 edited

Legend:

Unmodified
Added
Removed
  • trunk/data/defaultpresets.xml

    r3299 r3321  
    7474are supplied, then "values" will be treated as "display_values" and translated instead.
    7575-->
    76 <annotations>
     76<annotations xmlns="http://josm.openstreetmap.de/tagging-preset-1.0">
    7777  <group name="Highways" icon="presets/way_secondary.png">
    7878    <group name="Streets" icon="presets/way_secondary.png">
     
    134134        </item>
    135135        <item name="Trunk Link" icon="presets/trunk.png" type="way">
    136             <link href="http://wiki.openstreetmap.org/wiki/Tag:highway=trunk_link" 
     136            <link href="http://wiki.openstreetmap.org/wiki/Tag:highway=trunk_link"
    137137                  de.href="http://wiki.openstreetmap.org/wiki/DE:Tag:highway=trunk_link"/>
    138138            <label text="Edit Trunk Link" />
     
    154154        <separator/>
    155155        <item name="Primary" icon="presets/way_primary.png" type="way">
    156             <link href="http://wiki.openstreetmap.org/wiki/Tag:highway=primary" 
     156            <link href="http://wiki.openstreetmap.org/wiki/Tag:highway=primary"
    157157                  de.href="http://wiki.openstreetmap.org/wiki/DE:Tag:highway=primary" />
    158158            <label text="Edit Primary Road" />
     
    267267        </item>
    268268        <item name="Living Street" icon="presets/living_street.png" type="way">
    269             <link href="http://wiki.openstreetmap.org/wiki/Tag:highway=living_street" 
     269            <link href="http://wiki.openstreetmap.org/wiki/Tag:highway=living_street"
    270270                  de.href="http://wiki.openstreetmap.org/wiki/DE:Tag:highway=living_street" />
    271271            <label text="Edit Living Street" />
     
    743743    <group name="Barriers" icon="presets/barrier.png">
    744744
    745         <!-- *** node barriers *** -->   
     745        <!-- *** node barriers *** -->
    746746        <item name="Bollard" icon="presets/bollard.png" type="node,way">
    747747            <link href="http://wiki.openstreetmap.org/wiki/Tag:barrier=bollard" />
     
    757757        </item> <!-- bollard -->
    758758        <item name="Cycle Barrier" icon="presets/empty.png" type="node">
    759             <link de.href="http://de.wikipedia.org/wiki/Umlaufgitter" />
     759            <link href="http://de.wikipedia.org/wiki/Umlaufgitter" />
    760760            <key key="barrier" value="cycle_barrier" />
    761761        </item> <!-- cycle_barrier -->
     
    813813        </item> <!-- border_control -->
    814814        <separator/>
    815        
    816         <!-- *** linear barriers *** -->   
     815
     816        <!-- *** linear barriers *** -->
    817817        <item name="Hedge" icon="presets/empty.png" type="way,closedway,relation">
    818818            <link href="http://wiki.openstreetmap.org/wiki/Tag:barrier=hedge" />
     
    835835        </item> <!-- retaining_wall -->
    836836        <separator/>
    837        
    838         <!-- *** access *** -->   
     837
     838        <!-- *** access *** -->
    839839        <item name="Entrance" icon="presets/empty.png" type="node">
    840840            <label text="Edit Entrance" />
     
    938938            <check key="motorcar" text="Motorcar" default="off" delete_if_empty="true" />
    939939        </item> <!-- sally_port -->
    940        
     940
    941941    </group> <!-- Barriers -->
    942942  </group>
     
    13691369            <combo key="park_ride" text="Park and Ride" values="yes,no" default="" delete_if_empty="true" />
    13701370            <combo key="fee" text="Fee" values="yes,no" default="" delete_if_empty="true" />
    1371             <space /> 
     1371            <space />
    13721372            <text key="capacity" text="Capacity (overall)" default="" delete_if_empty="true" />
    13731373            <combo key="capacity:disabled" text="Spaces for Disabled" values="yes,no,unknown,1,2,3" default="" delete_if_empty="true" />
     
    27192719            <text key="name" text="Name" default="" delete_if_empty="true" />
    27202720            <combo key="opening_hours" text="Opening Hours" values="24/7,Mo-Fr 08:30-20:00,Tu-Su 08:00-15:00; Sa 08:00-12:00" default="" delete_if_empty="true" />
    2721         </item>   
     2721        </item>
    27222722        <item name="Sports" icon="presets/empty.png" type="node,closedway">
    27232723            <label text="Edit Sports Shop" />
  • trunk/src/org/openstreetmap/josm/data/gpx/WayPoint.java

    r2908 r3321  
    1212import org.openstreetmap.josm.tools.PrimaryDateParser;
    1313
    14 public class WayPoint extends WithAttributes implements Comparable<WayPoint>
    15 {
    16     public double time;
    17     public Color customColoring;
    18     public boolean drawLine;
    19     public int dir;
     14public class WayPoint extends WithAttributes implements Comparable<WayPoint> {
    2015
    2116    private static ThreadLocal<PrimaryDateParser> dateParser = new ThreadLocal<PrimaryDateParser>() {
     
    2419        }
    2520    };
     21
     22    public double time;
     23    public Color customColoring;
     24    public boolean drawLine;
     25    public int dir;
     26
     27    public WayPoint(LatLon ll) {
     28        coor = new CachedLatLon(ll);
     29    }
    2630
    2731    private final CachedLatLon coor;
     
    3337    public final EastNorth getEastNorth() {
    3438        return coor.getEastNorth();
    35     }
    36 
    37     public WayPoint(LatLon ll) {
    38         coor = new CachedLatLon(ll);
    3939    }
    4040
  • trunk/src/org/openstreetmap/josm/gui/preferences/PreferenceDialog.java

    r2824 r3321  
    2525import org.openstreetmap.josm.gui.help.ContextSensitiveHelpAction;
    2626import org.openstreetmap.josm.gui.help.HelpUtil;
     27import org.openstreetmap.josm.gui.preferences.PreferenceTabbedPane.ValidationListener;
    2728import org.openstreetmap.josm.tools.ImageProvider;
    2829import org.openstreetmap.josm.tools.WindowGeometry;
     
    9697            setCanceled(true);
    9798            setVisible(false);
     99            tpPreferences.validationListeners.clear();
    98100        }
    99101
     
    111113
    112114        public void actionPerformed(ActionEvent evt) {
     115            for (ValidationListener listener: tpPreferences.validationListeners) {
     116                if (!listener.validatePreferences())
     117                    return;
     118            }
     119
    113120            tpPreferences.savePreferences();
     121            tpPreferences.validationListeners.clear();
    114122            setCanceled(false);
    115123            setVisible(false);
  • trunk/src/org/openstreetmap/josm/gui/preferences/PreferenceTabbedPane.java

    r3248 r3321  
    4343    static private final Logger logger = Logger.getLogger(PreferenceTabbedPane.class.getName());
    4444
     45    /**
     46     * Allows PreferenceSettings to do validation of entered values when ok was pressed. If data are invalid then event can
     47     * return false to cancel closing of preferences dialog
     48     *
     49     */
     50    public interface ValidationListener {
     51        /**
     52         *
     53         * @return True if preferences can be saved
     54         */
     55        boolean validatePreferences();
     56    }
     57
    4558    private final static Collection<PreferenceSettingFactory> settingsFactory = new LinkedList<PreferenceSettingFactory>();
    4659    private final List<PreferenceSetting> settings = new ArrayList<PreferenceSetting>();
     
    5568    public final javax.swing.JTabbedPane displaycontent = new javax.swing.JTabbedPane();
    5669    public final javax.swing.JTabbedPane mapcontent = new javax.swing.JTabbedPane();
     70
     71    List<ValidationListener> validationListeners = new ArrayList<ValidationListener>();
     72
     73    /**
     74     * Add validation listener to currently open preferences dialog. Calling to removeValidationListener is not necessary, all listeners will
     75     * be automatically removed when dialog is closed
     76     * @param validationListener
     77     */
     78    public void addValidationListener(ValidationListener validationListener) {
     79        validationListeners.add(validationListener);
     80    }
    5781
    5882    /**
     
    244268        settingsFactory.add(new MapPaintPreference.Factory());
    245269        settingsFactory.add(new TaggingPresetPreference.Factory());
    246         if(!Main.applet)
     270        if(!Main.applet) {
    247271            settingsFactory.add(new PluginPreference.Factory());
     272        }
    248273        settingsFactory.add(Main.toolbar);
    249274        settingsFactory.add(new AudioPreference.Factory());
  • trunk/src/org/openstreetmap/josm/gui/preferences/StyleSourceEditor.java

    r3308 r3321  
    181181    }
    182182
     183    public boolean hasActiveStylesChanged() {
     184        return !activeStylesModel.getStyles().equals(Main.pref.getCollection(pref, Collections.<String>emptyList()));
     185    }
     186
     187    public Collection<String> getActiveStyles() {
     188        return activeStylesModel.getStyles();
     189    }
     190
     191    public void removeSource(String source) {
     192        activeStylesModel.remove(source);
     193    }
     194
    183195    public boolean finish() {
    184196        boolean changed = false;
     
    343355                i++;
    344356            }
     357            fireTableDataChanged();
     358        }
     359
     360        public void remove(String source) {
     361            data.remove(source);
    345362            fireTableDataChanged();
    346363        }
     
    804821                    // ignore the exception and return
    805822                    return;
    806                 warn(e);
     823                OsmTransferException ex = new OsmTransferException(e);
     824                ex.setUrl(url);
     825                warn(ex);
    807826                return;
    808827            }
     
    821840            if (fileChooser == null) {
    822841                this.fileChooser = new JFileChooser();
    823                 if(!isFile)
     842                if(!isFile) {
    824843                    fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
     844                }
    825845            }
    826846            return fileChooser;
  • trunk/src/org/openstreetmap/josm/gui/preferences/TaggingPresetPreference.java

    r3210 r3321  
    55
    66import java.awt.GridBagLayout;
     7import java.io.IOException;
     8import java.util.ArrayList;
    79import java.util.Collection;
    810import java.util.HashMap;
     11import java.util.List;
    912
    1013import javax.swing.BorderFactory;
    1114import javax.swing.JCheckBox;
     15import javax.swing.JLabel;
    1216import javax.swing.JMenu;
    1317import javax.swing.JMenuItem;
     18import javax.swing.JOptionPane;
    1419import javax.swing.JPanel;
    1520import javax.swing.JSeparator;
     
    1823
    1924import org.openstreetmap.josm.Main;
     25import org.openstreetmap.josm.gui.ExtendedDialog;
     26import org.openstreetmap.josm.gui.preferences.PreferenceTabbedPane.ValidationListener;
    2027import org.openstreetmap.josm.gui.tagging.TaggingPreset;
    2128import org.openstreetmap.josm.gui.tagging.TaggingPresetMenu;
     
    2330import org.openstreetmap.josm.gui.tagging.ac.AutoCompletionManager;
    2431import org.openstreetmap.josm.tools.GBC;
     32import org.xml.sax.SAXException;
     33import org.xml.sax.SAXParseException;
    2534
    2635public class TaggingPresetPreference implements PreferenceSetting {
     
    3645    private JCheckBox sortMenu;
    3746    private JCheckBox enableDefault;
     47
     48
     49    private ValidationListener validationListener = new ValidationListener() {
     50        @Override
     51        public boolean validatePreferences() {
     52            if (sources.hasActiveStylesChanged()) {
     53                List<String> sourcesToRemove = new ArrayList<String>();
     54                SOURCES:
     55                    for (String source: sources.getActiveStyles()) {
     56                        boolean canLoad = false;
     57                        try {
     58                            TaggingPreset.readAll(source, false);
     59                            canLoad = true;
     60                        } catch (IOException e) {
     61                            ExtendedDialog ed = new ExtendedDialog(Main.parent, tr("Error"),
     62                                    new String[] {tr("Yes"), tr("No"), tr("Cancel")});
     63                            ed.setContent(tr("Could not read tagging preset source: {0}\nDo you want to keep it?", source));
     64                            switch (ed.showDialog().getValue()) {
     65                            case 1:
     66                                continue SOURCES;
     67                            case 2:
     68                                sourcesToRemove.add(source);
     69                                continue SOURCES;
     70                            default:
     71                                return false;
     72                            }
     73                        } catch (SAXException e) {
     74                            // We will handle this in step with validation
     75                        }
     76
     77                        String errorMessage = null;
     78
     79                        try {
     80                            TaggingPreset.readAll(source, true);
     81                        } catch (IOException e) {
     82                            // Should not happen, but at least show message
     83                            JOptionPane.showMessageDialog(Main.parent, tr("Could not read tagging preset source {0}", source));
     84                            return false;
     85                        } catch (SAXParseException e) {
     86                            if (canLoad) {
     87                                errorMessage = tr("<html>Tagging preset source {0} can be loaded but it contains errors. " +
     88                                        "Do you really want to use it?<br><br><table width=600>Error is: [{1}:{2}] {3}</table></html>",
     89                                        source, e.getLineNumber(), e.getColumnNumber(), e.getMessage(), e.getMessage());
     90                            } else {
     91                                errorMessage = tr("<html>Unable to parse tagging preset source: {0}. " +
     92                                        "Do you really want to use it?<br><br><table width=400>Error is: [{1}:{2}] {3}</table></html>",
     93                                        source, e.getLineNumber(), e.getColumnNumber(), e.getMessage(), e.getMessage());
     94                            }
     95                        } catch (SAXException e) {
     96                            if (canLoad) {
     97                                errorMessage = tr("<html>Tagging preset source {0} can be loaded but it contains errors. " +
     98                                        "Do you really want to use it?<br><br><table width=600>Error is: {1}</table></html>",
     99                                        source,  e.getMessage(), e.getMessage());
     100                            } else {
     101                                errorMessage = tr("<html>Unable to parse tagging preset source: {0}. " +
     102                                        "Do you really want to use it?<br><br><table width=600>Error is: {3}</table></html>",
     103                                        source, e.getMessage(), e.getMessage());
     104                            }
     105
     106                        }
     107
     108                        if (errorMessage != null) {
     109                            int result = JOptionPane.showConfirmDialog(Main.parent, new JLabel(errorMessage), tr("Error"),
     110                                    JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.ERROR_MESSAGE);
     111
     112                            switch (result) {
     113                            case JOptionPane.YES_OPTION:
     114                                continue SOURCES;
     115                            case JOptionPane.NO_OPTION:
     116                                sourcesToRemove.add(source);
     117                                continue SOURCES;
     118                            default:
     119                                return false;
     120                            }
     121                        }
     122                    }
     123                for (String toRemove:sourcesToRemove) {
     124                    sources.removeSource(toRemove);
     125                }
     126                return true;
     127            }  else
     128                return true;
     129        }
     130    };
    38131
    39132    public void addGui(final PreferenceTabbedPane gui) {
     
    64157                }
    65158        );
     159        gui.addValidationListener(validationListener);
    66160    }
    67161
     
    82176     */
    83177    public static void initialize() {
    84         taggingPresets = TaggingPreset.readFromPreferences();
     178        taggingPresets = TaggingPreset.readFromPreferences(false);
     179        for (TaggingPreset tp: taggingPresets) {
     180            if (!(tp instanceof TaggingPresetSeparator)) {
     181                Main.toolbar.register(tp);
     182            }
     183        }
    85184        if (taggingPresets.isEmpty()) {
    86185            Main.main.menu.presetsMenu.setVisible(false);
  • trunk/src/org/openstreetmap/josm/gui/tagging/TaggingPreset.java

    r3289 r3321  
    3636import javax.swing.JPanel;
    3737import javax.swing.JTextField;
     38import javax.xml.transform.stream.StreamSource;
    3839
    3940import org.openstreetmap.josm.Main;
     
    5455import org.openstreetmap.josm.gui.tagging.ac.AutoCompletionItemPritority;
    5556import org.openstreetmap.josm.gui.tagging.ac.AutoCompletionList;
    56 import org.openstreetmap.josm.gui.tagging.ac.AutoCompletionManager;
    5757import org.openstreetmap.josm.io.MirroredInputStream;
    5858import org.openstreetmap.josm.tools.GBC;
     
    501501
    502502        public void setRequisite(String str) throws SAXException {
    503             if("required".equals(str))
     503            if("required".equals(str)) {
    504504                required = true;
    505             else if(!"optional".equals(str))
     505            } else if(!"optional".equals(str))
    506506                throw new SAXException(tr("Unknown requisite: {0}", str));
    507507        }
     
    522522        public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel) {
    523523            String cstring;
    524             if(count > 0 && !required)
     524            if(count > 0 && !required) {
    525525                cstring = "0,"+String.valueOf(count);
    526             else if(count > 0)
     526            } else if(count > 0) {
    527527                cstring = String.valueOf(count);
    528             else if(!required)
     528            } else if(!required) {
    529529                cstring = "0-...";
    530             else
     530            } else {
    531531                cstring = "1-...";
     532            }
    532533            if(locale_text == null) {
    533534                if (text != null) {
     
    544545            if(types != null){
    545546                JPanel pp = new JPanel();
    546                 for(String t : types)
     547                for(String t : types) {
    547548                    pp.add(new JLabel(ImageProvider.get("Mf_" + t)));
     549                }
    548550                p.add(pp, GBC.eol());
    549551            }
     
    563565                proles.add(new JLabel(tr("count")), GBC.std().insets(0,0,10,0));
    564566                proles.add(new JLabel(tr("elements")), GBC.eol());
    565                 for (Role i : roles)
     567                for (Role i : roles) {
    566568                    i.addToPanel(proles, sel);
     569                }
    567570                p.add(proles, GBC.eol());
    568571            }
     
    667670     */
    668671    private static Collection<String> allowedtypes = Arrays.asList(new String[]
    669     {marktr("way"), marktr("node"), marktr("relation"), marktr("closedway")});
     672                                                                              {marktr("way"), marktr("node"), marktr("relation"), marktr("closedway")});
    670673
    671674    static public List<String> getType(String types) throws SAXException {
     
    682685    }
    683686
    684     public static List<TaggingPreset> readAll(Reader in) throws SAXException {
     687    public static List<TaggingPreset> readAll(Reader in, boolean validate) throws SAXException {
    685688        XmlObjectParser parser = new XmlObjectParser();
    686689        parser.mapOnStart("item", TaggingPreset.class);
     
    700703        TaggingPresetMenu lastmenu = null;
    701704        Roles lastrole = null;
    702         parser.start(in);
     705
     706        if (validate) {
     707            parser.startWithValidation(in, "http://josm.openstreetmap.de/tagging-preset-1.0", new StreamSource(TaggingPreset.class.getResourceAsStream("tagging-preset.xsd")));
     708        } else {
     709            parser.start(in);
     710        }
    703711        while(parser.hasNext()) {
    704712            Object o = parser.next();
     
    713721                    lastmenu = tp;
    714722                    all.add(tp);
    715                     Main.toolbar.register(tp);
    716723
    717724                }
     
    727734                tp.setDisplayName();
    728735                all.add(tp);
    729                 Main.toolbar.register(tp);
    730736                lastrole = null;
    731737            } else {
     
    744750                        lastrole = null;
    745751                    }
    746                 }
    747                 else
     752                } else
    748753                    throw new SAXException(tr("Preset sub element without parent"));
    749754            }
     
    752757    }
    753758
    754     public static Collection<TaggingPreset> readAll(Collection<String> sources) {
     759    public static Collection<TaggingPreset> readAll(String source, boolean validate) throws SAXException, IOException {
     760        MirroredInputStream s = new MirroredInputStream(source);
     761        InputStream zip = s.getZipEntry("xml","preset");
     762        if(zip != null) {
     763            zipIcons = s.getFile();
     764        }
     765        InputStreamReader r;
     766        try
     767        {
     768            r = new InputStreamReader(zip == null ? s : zip, "UTF-8");
     769        }
     770        catch (UnsupportedEncodingException e)
     771        {
     772            r = new InputStreamReader(zip == null ? s: zip);
     773        }
     774        return TaggingPreset.readAll(new BufferedReader(r), validate);
     775    }
     776
     777    public static Collection<TaggingPreset> readAll(Collection<String> sources, boolean validate) {
    755778        LinkedList<TaggingPreset> allPresets = new LinkedList<TaggingPreset>();
    756         for(String source : sources)
    757         {
     779        for(String source : sources)  {
    758780            try {
    759                 MirroredInputStream s = new MirroredInputStream(source);
    760                 InputStream zip = s.getZipEntry("xml","preset");
    761                 if(zip != null) {
    762                     zipIcons = s.getFile();
    763                 }
    764                 InputStreamReader r;
    765                 try
    766                 {
    767                     r = new InputStreamReader(zip == null ? s : zip, "UTF-8");
    768                 }
    769                 catch (UnsupportedEncodingException e)
    770                 {
    771                     r = new InputStreamReader(zip == null ? s: zip);
    772                 }
    773                 allPresets.addAll(TaggingPreset.readAll(new BufferedReader(r)));
     781                allPresets.addAll(TaggingPreset.readAll(source, validate));
    774782            } catch (IOException e) {
    775783                e.printStackTrace();
     
    781789                );
    782790            } catch (SAXException e) {
     791                System.err.println(e.getMessage());
     792                System.err.println(source);
    783793                e.printStackTrace();
    784794                JOptionPane.showMessageDialog(
     
    804814    }
    805815
    806     public static Collection<TaggingPreset> readFromPreferences() {
    807         return readAll(getPresetSources());
     816    public static Collection<TaggingPreset> readFromPreferences(boolean validate) {
     817        return readAll(getPresetSources(), validate);
    808818    }
    809819
  • trunk/src/org/openstreetmap/josm/io/MirroredInputStream.java

    r3083 r3321  
    7272     * than one files have this extension, the last file whose name includes <code>namepart</code>
    7373     * is opened.
    74      * 
     74     *
    7575     * @param extension  the extension of the file we're looking for
    7676     * @param namepart the name part
     
    104104            if(file.getName().endsWith(".zip")) {
    105105                System.err.println(tr("Warning: failed to open file with extension ''{2}'' and namepart ''{3}'' in zip file ''{0}''. Exception was: {1}",
    106                 file.getName(), e.toString(), extension, namepart));
     106                        file.getName(), e.toString(), extension, namepart));
    107107            }
    108108        }
     
    140140    }
    141141
    142     private File checkLocal(URL url, String destDir, long maxTime) {
     142    private File checkLocal(URL url, String destDir, long maxTime) throws IOException {
    143143        String localPath = Main.pref.get("mirror." + url);
    144144        File file = null;
     
    171171            URLConnection conn = url.openConnection();
    172172            conn.setConnectTimeout(5000);
     173            conn.setReadTimeout(5000);
    173174            bis = new BufferedInputStream(conn.getInputStream());
    174175            bos = new BufferedOutputStream( new FileOutputStream(destDirFile));
     
    178179                bos.write(buffer, 0, length);
    179180            }
    180         } catch(IOException ioe) {
    181             if (file != null)
    182                 return file;
    183             return null;
    184181        } finally {
    185182            if (bis != null) {
  • trunk/src/org/openstreetmap/josm/io/OsmWriter.java

    r3012 r3321  
    3333public class OsmWriter extends XmlWriter implements Visitor {
    3434
    35     public final String DEFAULT_API_VERSION = "0.6";
     35    public static final String DEFAULT_API_VERSION = "0.6";
    3636
    3737    private boolean osmConform;
  • trunk/src/org/openstreetmap/josm/tools/XmlObjectParser.java

    r2676 r3321  
    1616import java.util.concurrent.BlockingQueue;
    1717
     18import javax.xml.parsers.SAXParser;
    1819import javax.xml.parsers.SAXParserFactory;
     20import javax.xml.transform.Source;
     21import javax.xml.validation.Schema;
     22import javax.xml.validation.SchemaFactory;
     23import javax.xml.validation.ValidatorHandler;
    1924
    2025import org.xml.sax.Attributes;
     26import org.xml.sax.ContentHandler;
    2127import org.xml.sax.InputSource;
    2228import org.xml.sax.Locator;
    2329import org.xml.sax.SAXException;
    2430import org.xml.sax.SAXParseException;
     31import org.xml.sax.XMLReader;
    2532import org.xml.sax.helpers.DefaultHandler;
     33import org.xml.sax.helpers.XMLFilterImpl;
    2634
    2735/**
     
    101109    }
    102110
     111    private class AddNamespaceFilter extends XMLFilterImpl {
     112
     113        private final String namespace;
     114
     115        public AddNamespaceFilter(String namespace) {
     116            this.namespace = namespace;
     117        }
     118
     119        @Override
     120        public void startElement (String uri, String localName, String qName, Attributes atts) throws SAXException {
     121            if ("".equals(uri)) {
     122                super.startElement(namespace, localName, qName, atts);
     123            } else {
     124                super.startElement(uri, localName, qName, atts);
     125            }
     126
     127        }
     128
     129    }
     130
    103131    private class Parser extends DefaultHandler {
    104132        Stack<Object> current = new Stack<Object>();
     
    271299    }
    272300
    273     public Iterable<Object> start(final Reader in) {
     301    private Iterable<Object> start(final Reader in, final ContentHandler contentHandler) {
    274302        new Thread("XML Reader"){
    275303            @Override public void run() {
    276304                try {
    277                     SAXParserFactory.newInstance().newSAXParser().parse(new InputSource(in), parser);
     305                    SAXParserFactory parserFactory = SAXParserFactory.newInstance();
     306                    parserFactory.setNamespaceAware(true);
     307                    SAXParser parser = parserFactory.newSAXParser();
     308                    XMLReader reader = parser.getXMLReader();
     309                    reader.setContentHandler(contentHandler);
     310                    reader.parse(new InputSource(in));
    278311                } catch (Exception e) {
    279312                    try {
     
    282315                    }
    283316                }
    284                 parser = null;
    285317                try {
    286318                    queue.put(EOS);
     
    290322        }.start();
    291323        return this;
     324    }
     325
     326    public Iterable<Object> start(final Reader in) {
     327        return start(in, parser);
     328    }
     329
     330    public Iterable<Object> startWithValidation(final Reader in, String namespace, Source schemaSource) throws SAXException {
     331        SchemaFactory factory =  SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
     332        Schema schema = factory.newSchema(schemaSource);
     333        ValidatorHandler validator = schema.newValidatorHandler();
     334        validator.setContentHandler(parser);
     335        validator.setErrorHandler(parser);
     336
     337        AddNamespaceFilter filter = new AddNamespaceFilter(namespace);
     338        filter.setContentHandler(validator);
     339
     340        return start(in, filter);
    292341    }
    293342
Note: See TracChangeset for help on using the changeset viewer.