001/*
002 *  Copyright 2018 Anyware Services
003 *
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package org.ametys.plugins.contenttypeseditor.edition;
017
018import java.util.Map;
019
020import org.xml.sax.Attributes;
021import org.xml.sax.SAXException;
022import org.xml.sax.helpers.DefaultHandler;
023
024/**
025 * This class is intended to be use as a simple helper to construct Map for i18n
026 * message from SAX events. <br>
027 * Each pair key/value will be put (as Strings) in the constructed Map
028 */
029public class I18nMessageHandler extends DefaultHandler
030{
031    /** The object being constructed */
032    private Map<String, String> _map;
033
034    /** Current characters from SAX events */
035    private StringBuffer _currentString;
036
037    /** The current key message */
038    private String _currentKey;
039
040    /** True when saxing element with "message" qName */
041    private boolean _message;
042
043    /**
044     * Construct a I18nMessageHandler
045     * 
046     * @param map The map representing each pair of key/value for i18n message
047     */
048    public I18nMessageHandler(Map<String, String> map)
049    {
050        this._map = map;
051    }
052
053    @Override
054    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
055    {
056        _message = false;
057        if (qName.equals("message"))
058        {
059            _message = true;
060            _currentString = new StringBuffer();
061            _currentKey = attributes.getValue("key");
062        }
063    }
064
065    @Override
066    public void characters(char[] ch, int start, int length) throws SAXException
067    {
068        if (_message)
069        {
070            _currentString.append(ch, start, length);
071        }
072    }
073
074    @Override
075    public void endElement(String uri, String localName, String qName) throws SAXException
076    {
077        if (qName.equals("message"))
078        {
079            String value = _currentString.toString();
080            _map.put(_currentKey, value);
081            _message = false;
082        }
083    }
084
085}