001/*
002 *  Copyright 2010 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.cms.transformation;
017
018import java.io.IOException;
019import java.io.InputStream;
020import java.util.Map;
021
022import org.apache.avalon.framework.service.ServiceException;
023import org.apache.cocoon.ProcessingException;
024import org.apache.cocoon.environment.ObjectModelHelper;
025import org.apache.cocoon.generation.Generator;
026import org.apache.cocoon.generation.ServiceableGenerator;
027import org.apache.excalibur.xml.sax.SAXParser;
028import org.xml.sax.InputSource;
029import org.xml.sax.SAXException;
030
031/**
032 * {@link Generator} which uses an {@link InputStream} from parent context.
033 */
034public class InputStreamGenerator extends ServiceableGenerator
035{
036    public void generate() throws IOException, SAXException, ProcessingException
037    {
038        SAXParser parser = null;
039        
040        try
041        {
042            Map parentContextParameters = (Map) objectModel.get(ObjectModelHelper.PARENT_CONTEXT);
043            
044            if (parentContextParameters == null)
045            {
046                throw new ProcessingException("Missing parent context");
047            }
048
049            try (InputStream is = (InputStream) parentContextParameters.get("source"))
050            {
051                if (is == null)
052                {
053                    throw new ProcessingException("Missing source parent context attr");
054                }
055                
056                InputSource inputSource = new InputSource(is);
057                parser = (SAXParser) this.manager.lookup(SAXParser.ROLE);
058                parser.parse(inputSource, super.xmlConsumer);
059            }
060        }
061        catch (ServiceException e)
062        {
063            throw new ProcessingException("Unable to get a SAX parser", e);
064        }
065        finally
066        {
067            this.manager.release(parser);
068        }
069    }
070}