001/*
002 *  Copyright 2016 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.util;
017
018import java.io.IOException;
019import java.io.InputStream;
020
021import org.apache.avalon.framework.component.Component;
022import org.apache.avalon.framework.logger.AbstractLogEnabled;
023import org.apache.avalon.framework.service.ServiceException;
024import org.apache.avalon.framework.service.ServiceManager;
025import org.apache.avalon.framework.service.Serviceable;
026import org.apache.excalibur.xml.sax.SAXParser;
027import org.xml.sax.InputSource;
028import org.xml.sax.SAXException;
029import org.xml.sax.helpers.DefaultHandler;
030
031/**
032 * Component with XML utils methods
033 */
034public class XMLUtils extends AbstractLogEnabled implements Component, Serviceable
035{
036    /** The avalon role */
037    public static final String ROLE = XMLUtils.class.getName();
038    
039    /** The sax parser */
040    protected SAXParser _saxParser;
041
042    public void service(ServiceManager manager) throws ServiceException
043    {
044        _saxParser = (SAXParser) manager.lookup(SAXParser.ROLE);
045    }
046    
047    /**
048     * Get a XML as a string and extract the text only
049     * @param is The inputstream of XML
050     * @return The text or null if the XML is not well formed
051     */
052    public String toString(InputStream is)
053    {
054        try
055        {
056            TxtHandler txtHandler = new TxtHandler();
057            _saxParser.parse(new InputSource(is), txtHandler);
058            return txtHandler.getValue();
059        }
060        catch (IOException | SAXException e)
061        {
062            getLogger().error("Cannot parse inputstream", e);
063            return null;
064        }
065    }
066    
067    final class TxtHandler extends DefaultHandler
068    {
069        private StringBuilder _internal = new StringBuilder();
070        
071        @Override
072        public void characters(char[] ch, int start, int length) throws SAXException
073        {
074            _internal.append(new String(ch, start, length));
075        }
076        
077        public String getValue()
078        {
079            return _internal.toString();
080        }
081    }
082}