001/*
002 *  Copyright 2009 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.core.cocoon;
017
018import java.util.Arrays;
019import java.util.HashSet;
020import java.util.Set;
021
022import org.apache.avalon.framework.configuration.Configuration;
023import org.apache.avalon.framework.configuration.ConfigurationException;
024import org.apache.cocoon.components.serializers.XMLSerializer;
025import org.xml.sax.SAXException;
026
027/**
028 * Inherits from cocoon's serializers block XMLSerializer.<p>
029 * Empty tags are not collapsed except the ones configured with
030 * <code>tags-to-collapse</code>.<br>
031 * If there is no such configuration, default tags to collaspe are:
032 * <ul>
033 *   <li>input</li>
034 *   <li>img</li>
035 *   <li>meta</li>
036 *   <li>link</li>
037 *   <li>hr</li>
038 *   <li>br</li>
039 * </ul>
040 */
041public class XHTMLFragmentSerializer extends XMLSerializer
042{
043    /** List of the tags to collapse. */
044    private static final Set<String> __COLLAPSE_TAGS = new HashSet<>(Arrays.asList(
045        new String[] {"input", "img", "meta", "link", "hr", "br"}));
046    
047    
048    /** Buffer to store tag to collapse. */
049    private Set<String> _tagsToCollapse;
050    
051    @Override
052    public void configure(Configuration conf) throws ConfigurationException
053    {
054        super.configure(conf);
055        
056        // Tags to collapse
057        String tagsToCollapse = conf.getChild("tags-to-collapse").getValue(null);
058        
059        if (tagsToCollapse != null)
060        {
061            _tagsToCollapse = new HashSet<>();
062            for (String tag : tagsToCollapse.split(","))
063            {
064                _tagsToCollapse.add(tag.trim());
065            }
066        }
067        else
068        {
069            _tagsToCollapse = __COLLAPSE_TAGS;
070        }
071    }
072    
073    @Override
074    public void endElementImpl(String uri, String local, String qual) throws SAXException
075    {
076        // If the element is not in the list of the tags to collapse, close it without collapsing
077        if (!_tagsToCollapse.contains(local))
078        {
079            this.closeElement(false);
080        }
081        
082        super.endElementImpl(uri, local, qual);
083    }
084    
085}