001/*
002 *  Copyright 2012 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.core.userpref;
017
018import java.io.IOException;
019import java.util.Map.Entry;
020
021import org.apache.cocoon.ProcessingException;
022import org.apache.cocoon.environment.ObjectModelHelper;
023import org.apache.cocoon.environment.Request;
024import org.apache.cocoon.generation.AbstractGenerator;
025import org.apache.cocoon.xml.AttributesImpl;
026import org.apache.cocoon.xml.XMLUtils;
027import org.xml.sax.SAXException;
028
029import org.ametys.core.userpref.UserPreferencesErrors;
030import org.ametys.runtime.i18n.I18nizableText;
031import org.ametys.runtime.parameter.Errors;
032
033/**
034 * Generates a list of errors.
035 */
036public class UserPreferencesErrorsGenerator extends AbstractGenerator
037{
038
039    @Override
040    public void generate() throws IOException, SAXException, ProcessingException
041    {
042        Request request = ObjectModelHelper.getRequest(objectModel);
043        
044        UserPreferencesErrors errors = (UserPreferencesErrors) request.getAttribute("user-prefs-errors");
045        
046        contentHandler.startDocument();
047        
048        XMLUtils.startElement(contentHandler, "errors");
049        
050        if (errors != null)
051        {
052            for (Entry<String, Errors> fieldErrors : errors.getErrors().entrySet())
053            {
054                String fieldId = fieldErrors.getKey();
055                Errors errorLabels = fieldErrors.getValue();
056                
057                AttributesImpl atts = new AttributesImpl();
058                atts.addCDATAAttribute("id", fieldId);
059                XMLUtils.startElement(contentHandler, "field", atts);
060                
061                for (I18nizableText label : errorLabels.getErrors())
062                {
063                    label.toSAX(contentHandler, "error");
064                }
065                
066                XMLUtils.endElement(contentHandler, "field");
067            }
068        }
069        
070        XMLUtils.endElement(contentHandler, "errors");
071        
072        contentHandler.endDocument();
073    }
074
075}