001/*
002 *  Copyright 2013 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.cart.generators;
017
018import java.io.IOException;
019import java.util.HashMap;
020import java.util.List;
021import java.util.Map;
022
023import org.apache.avalon.framework.service.ServiceException;
024import org.apache.avalon.framework.service.ServiceManager;
025import org.apache.cocoon.ProcessingException;
026import org.apache.cocoon.components.source.impl.SitemapSource;
027import org.apache.cocoon.environment.ObjectModelHelper;
028import org.apache.cocoon.environment.Request;
029import org.apache.cocoon.generation.ServiceableGenerator;
030import org.apache.cocoon.xml.AttributesImpl;
031import org.apache.cocoon.xml.XMLUtils;
032import org.apache.excalibur.source.SourceResolver;
033import org.xml.sax.SAXException;
034
035import org.ametys.core.user.CurrentUserProvider;
036import org.ametys.core.user.User;
037import org.ametys.core.user.UserIdentity;
038import org.ametys.core.user.UserManager;
039import org.ametys.core.util.DateUtils;
040import org.ametys.core.util.IgnoreRootHandler;
041import org.ametys.core.util.JSONUtils;
042import org.ametys.core.util.URIUtils;
043import org.ametys.plugins.cart.Cart;
044import org.ametys.plugins.cart.CartElement;
045import org.ametys.plugins.cart.ContentElement;
046import org.ametys.plugins.cart.QueryElement;
047import org.ametys.plugins.cart.ResourceElement;
048import org.ametys.plugins.repository.AmetysObjectResolver;
049import org.ametys.runtime.i18n.I18nizableText;
050
051/**
052 * SAX elements of a cart
053 */
054public class CartElementDetailsGenerator extends ServiceableGenerator
055{
056    /** The Ametys object resolver */
057    protected AmetysObjectResolver _resolver;
058    /** The current user provider */
059    protected CurrentUserProvider _userProvider;
060    /** The Json utils */
061    private JSONUtils _jsonUtils;
062    /** The source resolver */
063    private SourceResolver _sourceResolver;
064    /** The user manager */
065    private UserManager _userManager;
066    
067    @Override
068    public void service(ServiceManager smanager) throws ServiceException
069    {
070        super.service(smanager);
071        _resolver = (AmetysObjectResolver) smanager.lookup(AmetysObjectResolver.ROLE);
072        _jsonUtils = (JSONUtils) manager.lookup(JSONUtils.ROLE);
073        _sourceResolver = (SourceResolver) manager.lookup(SourceResolver.ROLE);
074        _userManager = (UserManager) smanager.lookup(UserManager.ROLE);
075        _userProvider = (CurrentUserProvider) smanager.lookup(CurrentUserProvider.ROLE);
076    }
077    
078    @Override
079    public void generate() throws IOException, SAXException, ProcessingException
080    {
081
082        Request request = ObjectModelHelper.getRequest(objectModel);
083        String id = request.getParameter("cartId");
084        
085        Cart cart = _resolver.resolveById(id);
086        UserIdentity user = _userProvider.getUser();
087        
088        contentHandler.startDocument();
089        
090        if (cart.canRead(user))
091        {
092            AttributesImpl attrs = new AttributesImpl();
093            attrs.addCDATAAttribute("id", cart.getId());
094            
095            XMLUtils.startElement(contentHandler, "cart", attrs);
096            
097            XMLUtils.createElement(contentHandler, "label", cart.getTitle());
098            XMLUtils.createElement(contentHandler, "description", cart.getDescription());
099            
100            try 
101            {
102                List<QueryElement> queries = cart.getQueryCartElements();
103                _saxQueries(queries);
104            } 
105            catch (Exception e)
106            {
107                throw new SAXException("Unable to sax queries", e);
108            }
109            
110            try 
111            {
112                List<ContentElement> contents = cart.getContentCartElements();
113                _saxContents(contents);
114            } 
115            catch (Exception e)
116            {
117                throw new SAXException("Unable to sax contents", e);
118            }
119            
120            try 
121            {
122                List<ResourceElement> resources = cart.getResourceCartElements();
123                _saxResources(resources);
124            } 
125            catch (Exception e)
126            {
127                throw new SAXException("Unable to sax resources", e);
128            }
129                    
130            XMLUtils.endElement(contentHandler, "cart");
131        }
132        else
133        {
134            XMLUtils.createElement(contentHandler, "not-allowed");
135        }
136        
137        contentHandler.endDocument();
138    }
139    
140    /**
141     * SAX resources of the cart
142     * @param resources The resources of the cart
143     * @throws IOException if an error occurred
144     * @throws SAXException if an error occurred while saxing
145     */
146    protected void _saxResources (List<ResourceElement> resources) throws IOException, SAXException
147    {
148        XMLUtils.startElement(contentHandler, "resources");
149        for (ResourceElement resource : resources)
150        { 
151            AttributesImpl attrs = new AttributesImpl();
152            attrs.addCDATAAttribute("id", resource.getId());
153            XMLUtils.startElement(contentHandler, "resource", attrs);
154            
155            _saxCartElement(resource, resource.getGroups().get(0));
156            
157            XMLUtils.endElement(contentHandler, "resource");
158        }                
159        XMLUtils.endElement(contentHandler, "resources");
160    }
161    
162    /**
163     * SAX the attributes of a cart element
164     * @param cartElement The element to sax
165     * @param group The group to sax with
166     * @throws SAXException if an error occurred while saxing
167     */
168    protected void _saxCartElement(CartElement cartElement, I18nizableText group) throws SAXException
169    {
170        cartElement.getTitle().toSAX(contentHandler, "title");            
171        
172        XMLUtils.createElement(contentHandler, "lastModification", DateUtils.dateToString(cartElement.getLastModified()));            
173        UserIdentity lastContributor = cartElement.getLastContributor();
174        User user = _userManager.getUser(lastContributor.getPopulationId(), lastContributor.getLogin());
175        
176        XMLUtils.createElement(contentHandler, "lastContributor", user.getFullName());
177        
178        group.toSAX(contentHandler, "group");
179    }
180    
181    /**
182     * SAX contents of the cart
183     * @param contents The contents of the cart
184     * @throws IOException if an error occurred
185     * @throws SAXException if an error occurred while saxing
186     */
187    protected void _saxContents (List<ContentElement> contents) throws IOException, SAXException
188    {
189        SitemapSource sitemapSource = null;
190        try
191        {
192            XMLUtils.startElement(contentHandler, "contents");
193            for (ContentElement content : contents)
194            {        
195                List<I18nizableText> groups = content.getGroups();
196                for (I18nizableText group : groups)
197                {
198                    XMLUtils.startElement(contentHandler, "content");
199                    _saxCartElement(content, group);                   
200                    
201                    String cocoonUrl = _contentToCocoonUrl(content);
202                    sitemapSource = (SitemapSource) _sourceResolver.resolveURI(cocoonUrl);
203                    sitemapSource.toSAX(new IgnoreRootHandler(contentHandler));
204                    XMLUtils.endElement(contentHandler, "content");
205                }
206               
207            }            
208            XMLUtils.endElement(contentHandler, "contents");
209        }
210        finally
211        {
212            resolver.release(sitemapSource);
213        }
214    }
215    
216    /**
217     * Returns the Cocoon pipeline URL that returns content details
218     * @param content The content
219     * @return The cocoon URL that returns the content details
220     */
221    protected String _contentToCocoonUrl(ContentElement content)
222    {
223        return "cocoon://_content.html?contentId=" + URIUtils.encodeParameter(content.getId()); 
224    }
225    
226    /**
227     * SAX queries of the cart
228     * @param queries The queries of the cart
229     * @throws IOException if an error occurred
230     * @throws SAXException if an error occurred while saxing
231     */
232    protected void _saxQueries (List<QueryElement> queries) throws IOException, SAXException
233    {
234        SitemapSource sitemapSource = null;
235        try
236        {
237            XMLUtils.startElement(contentHandler, "queries");
238            for (QueryElement query : queries)
239            {                                                
240                XMLUtils.startElement(contentHandler, "query");
241                _saxCartElement(query, query.getGroups().get(0));                
242                
243                String queryDescription = query.getDescription().getLabel();        
244                Map<String, Object> queryDetails = _jsonUtils.convertJsonToMap(queryDescription);
245                
246                String printPluginUrl = queryDetails.containsKey("printUrlPlugin") ? (String) queryDetails.get("printUrlPlugin") : "cms";
247                String printUrl = queryDetails.containsKey("printUrl") ? (String) queryDetails.get("printUrl") : "search/print.html";
248                @SuppressWarnings("unchecked")
249                Map<String, Object> exportParams = (Map<String, Object>) queryDetails.get("exportParams");
250                Map<String, String> params = new HashMap<>();
251                params.put("parameters", _jsonUtils.convertObjectToJson(exportParams));
252                
253                sitemapSource = (SitemapSource) _sourceResolver.resolveURI("cocoon://_plugins/" + printPluginUrl + "/" + printUrl + "?parameters=" + _jsonUtils.convertObjectToJson(exportParams), null, new HashMap<String, String>());
254                sitemapSource.toSAX(new IgnoreRootHandler(contentHandler));
255                XMLUtils.endElement(contentHandler, "query");
256            }            
257            XMLUtils.endElement(contentHandler, "queries");
258        }
259        finally
260        {
261            resolver.release(sitemapSource);
262        }
263    }
264        
265}