001/*
002 *  Copyright 2011 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.skinfactory.generators;
017
018import java.io.IOException;
019import java.io.InputStream;
020import java.util.Map;
021
022import org.apache.avalon.framework.service.ServiceException;
023import org.apache.avalon.framework.service.ServiceManager;
024import org.apache.cocoon.ProcessingException;
025import org.apache.cocoon.environment.ObjectModelHelper;
026import org.apache.cocoon.generation.ServiceableGenerator;
027import org.apache.cocoon.xml.XMLUtils;
028import org.apache.excalibur.source.Source;
029import org.apache.excalibur.xml.sax.SAXParser;
030import org.xml.sax.InputSource;
031import org.xml.sax.SAXException;
032
033import org.ametys.core.util.IgnoreRootHandler;
034
035/**
036 * Generates the model file with the modifications
037 */
038public class ChangeModelHash extends ServiceableGenerator
039{
040    private SAXParser _saxParser;
041    
042    @Override
043    public void service(ServiceManager smanager) throws ServiceException
044    {
045        super.service(smanager);
046        _saxParser = (SAXParser) manager.lookup(SAXParser.ROLE);
047    }
048
049    @Override
050    public void generate() throws IOException, SAXException, ProcessingException
051    {
052        contentHandler.startDocument();
053        XMLUtils.startElement(contentHandler, "CMS");
054        
055        Map parentContextParameters = (Map) objectModel.get(ObjectModelHelper.PARENT_CONTEXT);
056        if (parentContextParameters != null)
057        {
058            Source src = null;
059            src = resolver.resolveURI((String) parentContextParameters.get("modelUri"));
060            try (InputStream is = src.getInputStream())
061            {
062                _saxParser.parse(new InputSource(is), new IgnoreRootHandler(contentHandler));
063            }
064            finally
065            {
066                resolver.release(src);            
067            }
068            
069            String hash = (String) parentContextParameters.get("hash");
070            XMLUtils.createElement(contentHandler, "hash", hash);
071        }
072        
073        XMLUtils.endElement(contentHandler, "CMS");
074        contentHandler.endDocument();
075        
076    }
077    
078}