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