View Javadoc
1   /*
2    * Copyright (c) 2002-2014, Mairie de Paris
3    * All rights reserved.
4    *
5    * Redistribution and use in source and binary forms, with or without
6    * modification, are permitted provided that the following conditions
7    * are met:
8    *
9    *  1. Redistributions of source code must retain the above copyright notice
10   *     and the following disclaimer.
11   *
12   *  2. Redistributions in binary form must reproduce the above copyright notice
13   *     and the following disclaimer in the documentation and/or other materials
14   *     provided with the distribution.
15   *
16   *  3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its
17   *     contributors may be used to endorse or promote products derived from
18   *     this software without specific prior written permission.
19   *
20   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21   * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
24   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30   * POSSIBILITY OF SUCH DAMAGE.
31   *
32   * License 1.0
33   */
34  package fr.paris.lutece.plugins.shoppingcart.service.persistence;
35  
36  import fr.paris.lutece.plugins.shoppingcart.business.ShoppingCartItem;
37  import fr.paris.lutece.plugins.shoppingcart.business.ShoppingCartItemFilter;
38  import fr.paris.lutece.plugins.shoppingcart.service.provider.ShoppingCartItemProviderManagementService;
39  import fr.paris.lutece.portal.service.util.AppException;
40  import fr.paris.lutece.portal.service.util.AppLogService;
41  import fr.paris.lutece.portal.web.LocalVariables;
42  
43  import java.util.ArrayList;
44  import java.util.Date;
45  import java.util.List;
46  
47  import javax.servlet.http.HttpServletRequest;
48  import javax.servlet.http.HttpSession;
49  
50  import org.apache.commons.lang.StringUtils;
51  import org.apache.commons.lang.mutable.MutableInt;
52  
53  
54  /**
55   * Shopping cart persistence service that saves items into session
56   */
57  public class SessionPersistenceService implements IShoppingCartPersistenceService
58  {
59      /**
60       * Session key of the Boolean attribute that indicates whether the current
61       * user has items saved in session
62       */
63      public static final String SESSION_ATTRIBUTE_HAS_SESSION_ITEMS = "shoppingcart.hasSessionItems";
64  
65      private static final String SESSION_ATTRIBUTE_SHOPPING_CART = "shoppingcart.sessionShoppingCartItems";
66      private static final String SESSION_ATTRIBUTE_ID_SHOPPING_CART_ITEM = "shoppingcart.sessionIdShoppingCart";
67  
68      private static final String SERVICE_NAME = "shoppingcart.seccionPersistenceService";
69  
70      /**
71       * {@inheritDoc}
72       */
73      @Override
74      public void saveItem( ShoppingCartItem item )
75      {
76          if ( item.getDateCreation( ) == null )
77          {
78              item.setDateCreation( new Date( ) );
79          }
80  
81          SessionedShoppingCartItem sessionedItem = getSessionedShoppingCartItem( );
82          List<ShoppingCartItem> listItems;
83          if ( sessionedItem == null )
84          {
85              listItems = new ArrayList<ShoppingCartItem>( );
86              sessionedItem = new SessionedShoppingCartItem( listItems, true );
87              saveSessionedShoppingCartItem( sessionedItem );
88          }
89          else
90          {
91              listItems = sessionedItem.getItemList( );
92          }
93          item.setIdItem( getNewShoppingCartItemId( ) );
94          listItems.add( item );
95          HttpSession session = getSession( );
96          if ( session != null )
97          {
98              session.setAttribute( SESSION_ATTRIBUTE_HAS_SESSION_ITEMS, true );
99          }
100     }
101 
102     /**
103      * {@inheritDoc}
104      * @return True
105      */
106     @Override
107     public boolean supportAnonymousUsers( )
108     {
109         return true;
110     }
111 
112     /**
113      * {@inheritDoc}
114      */
115     @Override
116     public List<ShoppingCartItem> findItemsByFilter( ShoppingCartItemFilter filter )
117     {
118         List<ShoppingCartItem> listResult = null;
119         listResult = new ArrayList<ShoppingCartItem>( );
120         List<ShoppingCartItem> listItems;
121         SessionedShoppingCartItem sessionedItem = getSessionedShoppingCartItem( );
122         if ( sessionedItem != null )
123         {
124             listItems = sessionedItem.getItemList( );
125             for ( ShoppingCartItem item : listItems )
126             {
127                 if ( doesItemMatchFilter( item, filter ) )
128                 {
129                     listResult.add( item );
130                 }
131             }
132         }
133 
134         return listResult;
135     }
136 
137     /**
138      * {@inheritDoc}
139      */
140     @Override
141     public List<ShoppingCartItem> getItemsOfUser( String strUserName )
142     {
143         return getItemsOfUser( );
144     }
145 
146     /**
147      * {@inheritDoc}
148      */
149     @Override
150     public String getServiceName( )
151     {
152         return SERVICE_NAME;
153     }
154 
155     /**
156      * {@inheritDoc}
157      */
158     @Override
159     public void removeItemFromUserShoppingCart( String strUserName, int nIdShoppingCartItem,
160             boolean bNotifyProviderService )
161     {
162         SessionedShoppingCartItem sessionedItem = getSessionedShoppingCartItem( );
163         if ( sessionedItem != null && nIdShoppingCartItem > 0 )
164         {
165             List<ShoppingCartItem> listItems = sessionedItem.getItemList( );
166             ShoppingCartItem itemFound = null;
167             for ( ShoppingCartItem item : listItems )
168             {
169                 if ( item.getIdItem( ) == nIdShoppingCartItem )
170                 {
171                     itemFound = item;
172                     break;
173                 }
174             }
175             if ( itemFound != null )
176             {
177                 if ( bNotifyProviderService )
178                 {
179                     ShoppingCartItemProviderManagementService.notifyItemRemoval( itemFound );
180                 }
181                 listItems.remove( itemFound );
182             }
183         }
184     }
185 
186     /**
187      * {@inheritDoc}
188      */
189     @Override
190     public void emptyShoppingCartOfUser( String strUserName, boolean bNotifyProviderService )
191     {
192         SessionedShoppingCartItem sessionedItem = getSessionedShoppingCartItem( );
193         if ( sessionedItem != null )
194         {
195             if ( bNotifyProviderService )
196             {
197                 List<ShoppingCartItem> listItems = sessionedItem.getItemList( );
198                 for ( ShoppingCartItem item : listItems )
199                 {
200                     ShoppingCartItemProviderManagementService.notifyItemRemoval( item );
201                 }
202             }
203             sessionedItem.setNotifyProvider( false );
204             saveSessionedShoppingCartItem( null );
205         }
206     }
207 
208     /**
209      * {@inheritDoc}
210      */
211     @Override
212     public ShoppingCartItem findItemById( int nIdShoppingCartItem )
213     {
214         List<ShoppingCartItem> listItems = getItemsOfUser( );
215         for ( ShoppingCartItem item : listItems )
216         {
217             if ( item.getIdItem( ) == nIdShoppingCartItem )
218             {
219                 return item;
220             }
221         }
222         return null;
223     }
224 
225     /**
226      * Check if an item match values of a filter
227      * @param item The item to check
228      * @param filter The values that the item must have
229      * @return True if the item match the filter, false otherwise
230      */
231     private boolean doesItemMatchFilter( ShoppingCartItem item, ShoppingCartItemFilter filter )
232     {
233         if ( ( filter.getIdProvider( ) != null && !StringUtils.equals( filter.getIdProvider( ), item.getIdProvider( ) ) )
234                 || ( filter.getIdLot( ) > 0 && filter.getIdLot( ) != item.getIdLot( ) )
235                 || ( filter.getIdResource( ) != null && !StringUtils.equals( filter.getIdResource( ),
236                         item.getIdResource( ) ) )
237                 || ( filter.getIdUser( ) != null && !StringUtils.equals( filter.getIdUser( ), item.getIdUser( ) ) )
238                 || ( filter.getItemPrice( ) > 0d && filter.getItemPrice( ) == item.getItemPrice( ) )
239                 || ( filter.getResourceType( ) != null && !StringUtils.equals( filter.getResourceType( ),
240                         item.getResourceType( ) ) )
241                 || ( filter.getDateCreationMin( ) != null && filter.getDateCreationMin( ).getTime( ) > item
242                         .getDateCreation( ).getTime( ) )
243                 || ( filter.getDateCreationMax( ) != null && filter.getDateCreationMax( ).getTime( ) < item
244                         .getDateCreation( ).getTime( ) ) )
245         {
246             return false;
247         }
248         return true;
249     }
250 
251     /**
252      * Get the SessionedShoppingCartItem of the current user, if any.
253      * @return The SessionedShoppingCartItem of the current user or null if none
254      *         was found.
255      */
256     private SessionedShoppingCartItem getSessionedShoppingCartItem( )
257     {
258         HttpSession session = getSession( );
259         if ( session != null )
260         {
261             return (SessionedShoppingCartItem) session.getAttribute( SESSION_ATTRIBUTE_SHOPPING_CART );
262         }
263         AppLogService.error(
264                 "No request or session attached to this context : could not return the sessioned shopping card item",
265                 new AppException( ) );
266         return null;
267     }
268 
269     /**
270      * Save the SessionedShoppingCartItem of the current user into the session
271      * @param sessionedItem The item to save
272      */
273     private void saveSessionedShoppingCartItem( SessionedShoppingCartItem sessionedItem )
274     {
275         HttpSession session = getSession( );
276         if ( session != null )
277         {
278             session.setAttribute( SESSION_ATTRIBUTE_SHOPPING_CART, sessionedItem );
279             session.setAttribute( SESSION_ATTRIBUTE_HAS_SESSION_ITEMS, sessionedItem != null
280                     && sessionedItem.getItemList( ).size( ) > 0 );
281         }
282     }
283 
284     /**
285      * Get the session of the current context.
286      * @return The session of the current context, or null if it is not a
287      *         request context
288      */
289     private HttpSession getSession( )
290     {
291         HttpServletRequest request = LocalVariables.getRequest( );
292         if ( request != null )
293         {
294             return request.getSession( true );
295         }
296         AppLogService.error( "No request attached to this context : could not save the sessioned shopping card item",
297                 new AppException( ) );
298         return null;
299     }
300 
301     /**
302      * Get the items of the current user that are stored in session
303      * @return The items of the current user
304      */
305     private List<ShoppingCartItem> getItemsOfUser( )
306     {
307         SessionedShoppingCartItem sessionedItem = getSessionedShoppingCartItem( );
308         if ( sessionedItem == null )
309         {
310             sessionedItem = new SessionedShoppingCartItem( null, true );
311             saveSessionedShoppingCartItem( sessionedItem );
312         }
313         return new ArrayList<ShoppingCartItem>( sessionedItem.getItemList( ) );
314     }
315 
316     /**
317      * Get a new id for shopping cart items of a user
318      * @return The new id, or 0 if this is not a request session
319      */
320     private int getNewShoppingCartItemId( )
321     {
322         HttpSession session = getSession( );
323         if ( session != null )
324         {
325             MutableInt nCurrentId = (MutableInt) session.getAttribute( SESSION_ATTRIBUTE_ID_SHOPPING_CART_ITEM );
326             if ( nCurrentId == null )
327             {
328                 nCurrentId = new MutableInt( 1 );
329                 session.setAttribute( SESSION_ATTRIBUTE_ID_SHOPPING_CART_ITEM, nCurrentId );
330             }
331             else
332             {
333                 nCurrentId.increment( );
334             }
335             return nCurrentId.intValue( );
336         }
337         return 0;
338     }
339 }