KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > portal > coplets > basket > BasketManagerImpl


1 /*
2  * Copyright 2004-2005 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.apache.cocoon.portal.coplets.basket;
17
18 import java.io.File JavaDoc;
19 import java.io.FileInputStream JavaDoc;
20 import java.io.FileOutputStream JavaDoc;
21 import java.io.IOException JavaDoc;
22 import java.io.InputStreamReader JavaDoc;
23 import java.io.ObjectInputStream JavaDoc;
24 import java.io.ObjectOutputStream JavaDoc;
25 import java.lang.reflect.Constructor JavaDoc;
26 import java.util.ArrayList JavaDoc;
27 import java.util.HashMap JavaDoc;
28 import java.util.Iterator JavaDoc;
29 import java.util.List JavaDoc;
30 import java.util.Map JavaDoc;
31
32 import org.apache.avalon.excalibur.io.IOUtil;
33 import org.apache.avalon.framework.activity.Disposable;
34 import org.apache.avalon.framework.activity.Initializable;
35 import org.apache.avalon.framework.component.Component;
36 import org.apache.avalon.framework.context.Context;
37 import org.apache.avalon.framework.context.ContextException;
38 import org.apache.avalon.framework.context.Contextualizable;
39 import org.apache.avalon.framework.logger.AbstractLogEnabled;
40 import org.apache.avalon.framework.parameters.ParameterException;
41 import org.apache.avalon.framework.parameters.Parameterizable;
42 import org.apache.avalon.framework.parameters.Parameters;
43 import org.apache.avalon.framework.service.ServiceException;
44 import org.apache.avalon.framework.service.ServiceManager;
45 import org.apache.avalon.framework.service.Serviceable;
46 import org.apache.avalon.framework.thread.ThreadSafe;
47 import org.apache.cocoon.Constants;
48 import org.apache.cocoon.ProcessingException;
49 import org.apache.cocoon.components.ContextHelper;
50 import org.apache.cocoon.components.cron.CronJob;
51 import org.apache.cocoon.components.cron.JobScheduler;
52 import org.apache.cocoon.components.cron.ServiceableCronJob;
53 import org.apache.cocoon.environment.Request;
54 import org.apache.cocoon.environment.Session;
55 import org.apache.cocoon.portal.PortalService;
56 import org.apache.cocoon.portal.coplet.CopletData;
57 import org.apache.cocoon.portal.coplet.CopletInstanceData;
58 import org.apache.cocoon.portal.coplets.basket.events.AddItemEvent;
59 import org.apache.cocoon.portal.coplets.basket.events.ContentStoreEvent;
60 import org.apache.cocoon.portal.coplets.basket.events.CleanBriefcaseEvent;
61 import org.apache.cocoon.portal.coplets.basket.events.MoveItemEvent;
62 import org.apache.cocoon.portal.coplets.basket.events.RefreshBasketEvent;
63 import org.apache.cocoon.portal.coplets.basket.events.RemoveItemEvent;
64 import org.apache.cocoon.portal.coplets.basket.events.ShowBasketEvent;
65 import org.apache.cocoon.portal.coplets.basket.events.ShowItemEvent;
66 import org.apache.cocoon.portal.coplets.basket.events.UploadItemEvent;
67 import org.apache.cocoon.portal.event.EventManager;
68 import org.apache.cocoon.portal.event.Receiver;
69 import org.apache.cocoon.portal.layout.impl.CopletLayout;
70 import org.apache.cocoon.servlet.multipart.Part;
71 import org.apache.cocoon.servlet.multipart.PartOnDisk;
72 import org.apache.cocoon.util.ClassUtils;
73 import org.apache.excalibur.source.Source;
74 import org.apache.excalibur.source.SourceResolver;
75
76 /**
77  * This is the implementation of the basket manager
78  *
79  * @version CVS $Id: BasketManagerImpl.java 291593 2005-09-26 10:49:55Z cziegeler $
80  */

81 public class BasketManagerImpl
82 extends AbstractLogEnabled
83 implements BasketManager, Serviceable, Receiver, Contextualizable, Initializable, Disposable, Parameterizable, ThreadSafe, Component {
84     
85     /** The service manager */
86     protected ServiceManager manager;
87     
88     /** The component context */
89     protected Context context;
90     
91     /** The configuration for storing baskets */
92     protected String JavaDoc directory;
93     
94     /** The class name of the basket */
95     protected String JavaDoc basketClassName = Basket.class.getName();
96     
97     /** The class name of the briefcase */
98     protected String JavaDoc briefcaseClassName = Briefcase.class.getName();
99
100     /** The class name of the folder */
101     protected String JavaDoc folderClassName = Folder.class.getName();
102
103     /** All actions for a basket */
104     protected List JavaDoc basketActions = new ArrayList JavaDoc();
105     
106     /** All actions for a briefcase */
107     protected List JavaDoc briefcaseActions = new ArrayList JavaDoc();
108     
109     /** All batches */
110     protected List JavaDoc batches = new ArrayList JavaDoc();
111     
112     /** Scheduler */
113     protected JobScheduler scheduler;
114     
115     /* (non-Javadoc)
116      * @see org.apache.avalon.framework.parameters.Parameterizable#parameterize(org.apache.avalon.framework.parameters.Parameters)
117      */

118     public void parameterize(Parameters parameters) throws ParameterException {
119         this.directory = parameters.getParameter("directory", this.directory);
120         this.basketClassName = parameters.getParameter("basket-class", this.basketClassName);
121         this.briefcaseClassName = parameters.getParameter("briefcase-class", this.briefcaseClassName);
122         this.folderClassName = parameters.getParameter("folder-class", this.folderClassName);
123         String JavaDoc[] names = parameters.getNames();
124         if ( names != null ) {
125             for(int i=0; i<names.length; i++) {
126                 final String JavaDoc current = names[i];
127                 if ( current.startsWith("basket:action:") ) {
128                     final String JavaDoc value = parameters.getParameter(current);
129                     final String JavaDoc key = current.substring(14);
130                     this.basketActions.add(new ActionInfo(key, value));
131                 } else if ( current.startsWith("briefcase:action:") ) {
132                     final String JavaDoc value = parameters.getParameter(current);
133                     final String JavaDoc key = current.substring(17);
134                     this.briefcaseActions.add(new ActionInfo(key, value));
135                 }
136             }
137         }
138     }
139
140     /* (non-Javadoc)
141      * @see org.apache.avalon.framework.context.Contextualizable#contextualize(org.apache.avalon.framework.context.Context)
142      */

143     public void contextualize(Context context) throws ContextException {
144         this.context = context;
145         this.directory = ((File JavaDoc)context.get(Constants.CONTEXT_WORK_DIR)).getAbsolutePath();
146     }
147
148     /* (non-Javadoc)
149      * @see org.apache.avalon.framework.service.Serviceable#service(org.apache.avalon.framework.service.ServiceManager)
150      */

151     public void service(ServiceManager manager) throws ServiceException {
152         this.manager = manager;
153         this.scheduler = (JobScheduler)this.manager.lookup(JobScheduler.ROLE);
154     }
155
156     /* (non-Javadoc)
157      * @see org.apache.avalon.framework.activity.Disposable#dispose()
158      */

159     public void dispose() {
160         if ( this.manager != null ) {
161             this.manager.release(this.scheduler);
162             this.scheduler = null;
163             this.manager = null;
164         }
165     }
166     
167     /* (non-Javadoc)
168      * @see org.apache.avalon.framework.activity.Initializable#initialize()
169      */

170     public void initialize() throws Exception JavaDoc {
171         EventManager eventManager = null;
172         try {
173             eventManager = (EventManager) this.manager.lookup(EventManager.ROLE);
174             eventManager.subscribe(this);
175         } finally {
176             this.manager.release(eventManager);
177         }
178     }
179
180     /**
181      * @see Receiver
182      */

183     public void inform(ContentStoreEvent event, PortalService service) {
184         // dispatch
185
final Session session = ContextHelper.getRequest(this.context).getSession();
186         if ( event instanceof AddItemEvent ) {
187             
188             this.processAddItemEvent((AddItemEvent)event);
189             
190         } else if (event instanceof RemoveItemEvent ){
191             
192             this.processRemoveItemEvent((RemoveItemEvent)event);
193             
194         } else if (event instanceof RefreshBasketEvent) {
195             
196             session.removeAttribute(ALL_BRIEFCASES_KEY);
197             
198         } else if (event instanceof CleanBriefcaseEvent) {
199             
200             this.processCleanBriefcaseEvent((CleanBriefcaseEvent)event, session);
201             
202         } else if ( event instanceof UploadItemEvent ) {
203             
204             this.processUploadItemEvent((UploadItemEvent)event);
205         } else if ( event instanceof ShowItemEvent ) {
206             
207             this.processShowItemEvent((ShowItemEvent)event);
208         } else if ( event instanceof ShowBasketEvent ) {
209             
210             this.processShowBasketEvent((ShowBasketEvent)event, session);
211         } else if ( event instanceof MoveItemEvent ) {
212             ContentStore source = ((MoveItemEvent)event).getContentStore();
213             ContentStore target = ((MoveItemEvent)event).getTarget();
214             Object JavaDoc item = ((MoveItemEvent)event).getItem();
215             source.removeItem(item);
216             target.addItem(item);
217             this.saveContentStore(source);
218             this.saveContentStore(target);
219         }
220     }
221
222     /**
223      * Process an upload and add the item to the content store
224      * @param event The event triggering the action
225      */

226     protected void processUploadItemEvent(UploadItemEvent event) {
227         final ContentStore store = event.getContentStore();
228         final Request req = ContextHelper.getRequest(this.context);
229         final List JavaDoc paramNames = event.getItemNames();
230         final Iterator JavaDoc i = paramNames.iterator();
231         while ( i.hasNext() ) {
232             final String JavaDoc name = (String JavaDoc)i.next();
233             final Object JavaDoc o = req.get(name);
234             if ( o != null && o instanceof Part) {
235                 final Part file = (Part)o;
236                 try {
237                     byte[] c = IOUtil.toByteArray(file.getInputStream());
238                     ContentItem ci = new ContentItem(file.getFileName(), true);
239                     ci.setContent(c);
240                     store.addItem(ci);
241                 } catch (Exception JavaDoc ignore) {
242                     // ignore the exception
243
}
244                 if ( file instanceof PartOnDisk) {
245                     ((PartOnDisk)file).getFile().delete();
246                 }
247             }
248         }
249     }
250
251     /**
252      * Show one item of the basket
253      * @param event The event triggering the action
254      */

255     protected void processShowItemEvent(ShowItemEvent event) {
256         if ( event.getItem() instanceof ContentItem ) {
257             PortalService service = null;
258             try {
259                 service = (PortalService) this.manager.lookup(PortalService.ROLE);
260                 
261                 ContentItem ci = (ContentItem)event.getItem();
262                 CopletLayout layout = (CopletLayout) event.getLayout();
263                 CopletInstanceData cid = null;
264                 if ( ci.isContent() ) {
265                     CopletData copletData = service.getComponentManager().getProfileManager().getCopletData(event.getCopletDataId());
266                     cid = service.getComponentManager().getCopletFactory().newInstance(copletData);
267                     cid.setAttribute("item-content", ci.getContent());
268                 } else {
269                     if ( ci.getURL() != null ) {
270                         SourceResolver resolver = null;
271                         Source source = null;
272                         String JavaDoc url = null;
273                         try {
274                             resolver = (SourceResolver)this.manager.lookup(SourceResolver.ROLE);
275                             url = ci.getURL();
276                             source = resolver.resolveURI(url);
277                             CopletData copletData = service.getComponentManager().getProfileManager().getCopletData(event.getCopletDataId());
278                             cid = service.getComponentManager().getCopletFactory().newInstance(copletData);
279                             cid.setAttribute("item-content", IOUtil.toByteArray(source.getInputStream()));
280                         } catch (IOException JavaDoc se) {
281                             this.getLogger().warn("Unable to get content for " + url, se);
282                         } catch (ServiceException se) {
283                             this.getLogger().warn("Unable to get source resolver.", se);
284                         } finally {
285                             if ( source != null ) {
286                                 resolver.release(source);
287                             }
288                             this.manager.release(resolver);
289                         }
290                         
291                     } else {
292                         final CopletInstanceData original = service.getComponentManager().getProfileManager().getCopletInstanceData(ci.getCopletId());
293                         final CopletData copletData = original.getCopletData();
294                         cid = service.getComponentManager().getCopletFactory().newInstance(copletData);
295                         Map JavaDoc attributes = (Map JavaDoc) ci.getAttribute("coplet-attributes");
296                         Iterator JavaDoc i = attributes.entrySet().iterator();
297                         while ( i.hasNext() ) {
298                             Map.Entry JavaDoc entry = (Map.Entry JavaDoc)i.next();
299                             cid.setAttribute(entry.getKey().toString(), entry.getValue());
300                         }
301                         // now copy the original attributes
302
attributes = original.getAttributes();
303                         i = attributes.entrySet().iterator();
304                         while ( i.hasNext() ) {
305                             Map.Entry JavaDoc entry = (Map.Entry JavaDoc)i.next();
306                             cid.setAttribute(entry.getKey().toString(), entry.getValue());
307                         }
308                     }
309                 }
310                 layout.setCopletInstanceData(cid);
311             } catch (ProcessingException pe) {
312                 this.getLogger().warn("Unable to create new instance.", pe);
313             } catch (ServiceException se) {
314                 this.getLogger().warn("Unable to lookup portal service.", se);
315             } finally {
316                 this.manager.release(service);
317             }
318         }
319     }
320
321     /**
322      * Show the selected basket
323      */

324     protected void processShowBasketEvent(ShowBasketEvent event, Session session) {
325         Briefcase briefcase = (Briefcase)this.loadContentStore( BRIEFCASE_KEY, event.getBasketId() );
326         session.setAttribute(BRIEFCASE_KEY, briefcase);
327     }
328     
329     /**
330      * Cleaning a briefcase or all
331      * @param event The triggering event
332      * @param session The session
333      */

334     protected void processCleanBriefcaseEvent(CleanBriefcaseEvent event, Session session) {
335         final Briefcase briefcase = (Briefcase)event.getContentStore();
336         final List JavaDoc baskets = (List JavaDoc)session.getAttribute(ALL_BRIEFCASES_KEY);
337         if ( briefcase == null) {
338             // remove all briefcases
339
if ( baskets != null ) {
340                 Iterator JavaDoc i = baskets.iterator();
341                 while (i.hasNext()) {
342                     ContentStoreDescription entry = (ContentStoreDescription)i.next();
343                     this.deleteContentStore(BRIEFCASE_KEY, entry.id);
344                 }
345                 session.removeAttribute(ALL_BRIEFCASES_KEY);
346             }
347         } else {
348             // remove one briefcase
349
this.deleteContentStore(BRIEFCASE_KEY, briefcase.getId());
350             if ( baskets != null ) {
351                 Iterator JavaDoc i = baskets.iterator();
352                 boolean found = false;
353                 while (i.hasNext() && !found) {
354                     ContentStoreDescription entry = (ContentStoreDescription)i.next();
355                     if ( entry.id.equals(briefcase.getId())) {
356                         found = true;
357                         i.remove();
358                     }
359                 }
360             }
361         }
362     }
363
364     /**
365      * This method processes removing one item from a content store
366      * @param event The event triggering the action
367      */

368     protected void processRemoveItemEvent(RemoveItemEvent event) {
369         final Object JavaDoc item = event.getItem();
370         final ContentStore store = event.getContentStore();
371         
372         store.removeItem(item);
373         
374         this.saveContentStore(store);
375     }
376
377     /**
378      * This method processes adding one item to a content store
379      * @param event The event triggering the action
380      */

381     protected void processAddItemEvent(AddItemEvent event) {
382         final ContentStore store = event.getContentStore();
383         final Object JavaDoc item = event.getItem();
384         if ( item instanceof ContentItem ) {
385             ContentItem ci = (ContentItem)item;
386
387                 if ( ci.isContent() ) {
388                     SourceResolver resolver = null;
389                     Source source = null;
390                     String JavaDoc url = null;
391                     try {
392                         resolver = (SourceResolver)this.manager.lookup(SourceResolver.ROLE);
393                         url = ci.getURL();
394                         if ( url == null ) {
395                         // copy coplet attributes
396
PortalService service = null;
397                         try {
398                             service = (PortalService) this.manager.lookup(PortalService.ROLE);
399                             CopletInstanceData cid = service.getComponentManager().getProfileManager().getCopletInstanceData(ci.getCopletId());
400                             url = "coplet://" + ci.getCopletId();
401                             Map JavaDoc attributes = new HashMap JavaDoc();
402                             Iterator JavaDoc i = cid.getAttributes().entrySet().iterator();
403                             while ( i.hasNext() ) {
404                                 Map.Entry JavaDoc entry = (Map.Entry JavaDoc)i.next();
405                                 attributes.put(entry.getKey(), entry.getValue());
406                             }
407                             i = cid.getCopletData().getAttributes().entrySet().iterator();
408                             while ( i.hasNext() ) {
409                                 Map.Entry JavaDoc entry = (Map.Entry JavaDoc)i.next();
410                                 attributes.put(entry.getKey(), entry.getValue());
411                             }
412                             ci.setAttribute("coplet-attributes", attributes);
413                         } catch (ServiceException se) {
414                             this.getLogger().warn("Unable to lookup portal service.", se);
415                         } finally {
416                             this.manager.release(service);
417                         }
418                         }
419                         source = resolver.resolveURI(url);
420                         ci.setContent(IOUtil.toByteArray(source.getInputStream()));
421                     } catch (IOException JavaDoc se) {
422                         this.getLogger().warn("Unable to get content for " + url, se);
423                     } catch (ServiceException se) {
424                         this.getLogger().warn("Unable to get source resolver.", se);
425                     } finally {
426                         if ( source != null ) {
427                             resolver.release(source);
428                         }
429                         this.manager.release(resolver);
430                     }
431                 } else if ( ci.getURL() == null ) {
432                     // copy coplet attributes
433
PortalService service = null;
434                     try {
435                         service = (PortalService) this.manager.lookup(PortalService.ROLE);
436                         CopletInstanceData cid = service.getComponentManager().getProfileManager().getCopletInstanceData(ci.getCopletId());
437                         Map JavaDoc attributes = new HashMap JavaDoc();
438                         Iterator JavaDoc i = cid.getAttributes().entrySet().iterator();
439                         while ( i.hasNext() ) {
440                             Map.Entry JavaDoc entry = (Map.Entry JavaDoc)i.next();
441                             attributes.put(entry.getKey(), entry.getValue());
442                         }
443                         i = cid.getCopletData().getAttributes().entrySet().iterator();
444                         while ( i.hasNext() ) {
445                             Map.Entry JavaDoc entry = (Map.Entry JavaDoc)i.next();
446                             attributes.put(entry.getKey(), entry.getValue());
447                         }
448                         ci.setAttribute("coplet-attributes", attributes);
449                     } catch (ServiceException se) {
450                         this.getLogger().warn("Unable to lookup portal service.", se);
451                     } finally {
452                         this.manager.release(service);
453                     }
454                 }
455             store.addItem(ci);
456         } else {
457             store.addItem(item);
458         }
459         this.saveContentStore(store);
460     }
461
462     /**
463      * Save the content store if it is a briefcase or a folder
464      */

465     protected void saveContentStore(ContentStore store) {
466         if ( store instanceof Briefcase ) {
467             this.saveContentStore(BRIEFCASE_KEY, store);
468         } else if ( store instanceof Folder ) {
469             this.saveContentStore(FOLDER_KEY, store);
470         }
471     }
472
473     /**
474      * Load the content store for a single user
475      * @param type The type of the content store (briefcase or folder)
476      * @return The content store or null
477      */

478     protected ContentStore loadContentStore(String JavaDoc type, String JavaDoc userId) {
479         if ( this.directory != null ) {
480             final String JavaDoc suffix;
481             if ( FOLDER_KEY.equals(type) ) {
482                 suffix = ".folder";
483             } else {
484                 suffix = ".briefcase";
485             }
486             File JavaDoc file = new File JavaDoc(this.directory, userId + suffix);
487             if ( file.exists() ) {
488                 try {
489                     ObjectInputStream JavaDoc ois = new ObjectInputStream JavaDoc(new FileInputStream JavaDoc(file));
490                     ContentStore store = (ContentStore)ois.readObject();
491                     ois.close();
492                     return store;
493                 } catch (Exception JavaDoc ignore) {
494                     // ignore this
495
}
496             }
497         }
498         return null;
499     }
500     
501     /**
502      * Load a content store
503      * @param type The type of the content store (briefcase or folder)
504      */

505     protected ContentStore loadContentStore(String JavaDoc type) {
506         ContentStore store = null;
507         String JavaDoc user = this.getUser();
508         if ( user != null ) {
509             store = this.loadContentStore(type, user);
510         }
511         if ( store == null && user != null ) {
512             try {
513                 final String JavaDoc clazzName;
514                 if ( BRIEFCASE_KEY.equals(type) ) {
515                     clazzName = this.briefcaseClassName;
516                 } else {
517                     clazzName = this.folderClassName;
518                 }
519                 
520                 final Class JavaDoc clazz = ClassUtils.loadClass(clazzName);
521                 final Constructor JavaDoc constructor = clazz.getConstructor(new Class JavaDoc[] {String JavaDoc.class});
522                 
523                 store = (ContentStore)constructor.newInstance(new Object JavaDoc[] {user});
524             } catch (Exception JavaDoc ignore) {
525                 if ( BRIEFCASE_KEY.equals(type) ) {
526                     store = new Briefcase(user);
527                 } else {
528                     store = new Folder(user);
529                 }
530             }
531         }
532         return store;
533     }
534     
535     /**
536      * Delete the content store for a user
537      */

538     protected void deleteContentStore(String JavaDoc type, String JavaDoc userId) {
539         final String JavaDoc suffix;
540         if ( FOLDER_KEY.equals(type) ) {
541             suffix = ".folder";
542         } else {
543             suffix = ".briefcase";
544         }
545         if ( this.directory != null ) {
546             File JavaDoc file = new File JavaDoc(this.directory, userId+suffix);
547             if ( file.exists() ) {
548                 file.delete();
549             }
550         }
551     }
552
553     /**
554      * Save the content store for a single user
555      */

556     protected void saveContentStore(String JavaDoc type, ContentStore store) {
557         final String JavaDoc userId = store.getId();
558         final String JavaDoc suffix;
559         if ( FOLDER_KEY.equals(type) ) {
560             suffix = ".folder";
561         } else {
562             suffix = ".briefcase";
563         }
564         
565         if ( this.directory != null ) {
566             File JavaDoc file = new File JavaDoc(this.directory, userId+suffix);
567             try {
568                 if ( !file.exists() ) {
569                     file.createNewFile();
570                     file = new File JavaDoc(this.directory, userId+suffix);
571                 }
572                 ObjectOutputStream JavaDoc oos = new ObjectOutputStream JavaDoc(new FileOutputStream JavaDoc(file));
573                 oos.writeObject(store);
574                 oos.close();
575             } catch (Exception JavaDoc ignore) {
576                 // ignore this
577
}
578         }
579     }
580     
581     /**
582      * Get briefcases of all users
583      */

584     protected List JavaDoc loadBriefcases() {
585         if ( this.directory != null ) {
586             File JavaDoc directory = new File JavaDoc(this.directory);
587             if ( directory.exists()) {
588                 List JavaDoc briefcases = new ArrayList JavaDoc();
589                 File JavaDoc[] files = directory.listFiles();
590                 for(int i=0; i<files.length;i++) {
591                     String JavaDoc user = files[i].getName();
592                     int pos = user.indexOf(".briefcase");
593                     if ( pos != -1 ) {
594                         user = user.substring(0, pos);
595                         ContentStore store = this.loadContentStore(BRIEFCASE_KEY, user);
596                         if ( store != null ) {
597                             ContentStoreDescription bd = new ContentStoreDescription();
598                             bd.id = user;
599                             bd.size = store.contentSize();
600                             briefcases.add(bd);
601                         }
602                     }
603                 }
604                 return briefcases;
605             }
606         }
607         return null;
608     }
609     
610     /* (non-Javadoc)
611      * @see org.apache.cocoon.portal.coplets.basket.BasketManager#getBasket()
612      */

613     public Basket getBasket() {
614         Session session = ContextHelper.getRequest(this.context).getSession();
615         Basket basket = (Basket) session.getAttribute(BASKET_KEY);
616         if ( basket == null ) {
617             final String JavaDoc user = this.getUser();
618             try {
619                 final Class JavaDoc clazz = ClassUtils.loadClass(this.basketClassName);
620                 final Constructor JavaDoc constructor = clazz.getConstructor(new Class JavaDoc[] {String JavaDoc.class});
621                 
622                 basket = (Basket)constructor.newInstance(new Object JavaDoc[] {user});
623             } catch (Exception JavaDoc ignore) {
624                 basket = new Basket(user);
625             }
626             session.setAttribute(BASKET_KEY, basket);
627         }
628         return basket;
629     }
630    
631     /* (non-Javadoc)
632      * @see org.apache.cocoon.portal.coplets.basket.BasketManager#getBriefcase()
633      */

634     public Briefcase getBriefcase() {
635         Session session = ContextHelper.getRequest(this.context).getSession();
636         Briefcase briefcase = (Briefcase) session.getAttribute(BRIEFCASE_KEY);
637         if ( briefcase == null ) {
638             briefcase = (Briefcase)this.loadContentStore(BRIEFCASE_KEY);
639             session.setAttribute(BRIEFCASE_KEY, briefcase);
640         }
641         return briefcase;
642     }
643     
644     public Folder getFolder() {
645         Session session = ContextHelper.getRequest(this.context).getSession();
646         Folder folder = (Folder) session.getAttribute(FOLDER_KEY);
647         if ( folder == null ) {
648             folder = (Folder)this.loadContentStore(FOLDER_KEY);
649             session.setAttribute(FOLDER_KEY, folder);
650         }
651         return folder;
652     }
653
654     /* (non-Javadoc)
655      * @see org.apache.cocoon.portal.coplets.basket.BasketManager#getBriefcaseDescriptions()
656      */

657     public List JavaDoc getBriefcaseDescriptions() {
658         Session session = ContextHelper.getRequest(this.context).getSession();
659         List JavaDoc briefcases = (List JavaDoc)session.getAttribute(ALL_BRIEFCASES_KEY);
660         if ( briefcases == null ) {
661             briefcases = this.loadBriefcases();
662             if (briefcases == null) {
663                 briefcases = new ArrayList JavaDoc();
664             }
665             session.setAttribute(ALL_BRIEFCASES_KEY, briefcases);
666         }
667         return briefcases;
668     }
669     
670     /**
671      * Get the current user
672      */

673     protected String JavaDoc getUser() {
674         PortalService service = null;
675         try {
676             service = (PortalService)this.manager.lookup(PortalService.ROLE);
677             return service.getComponentManager().getProfileManager().getUser().getUserName();
678         } catch (ServiceException ignore) {
679             // ignore this
680
} finally {
681             this.manager.release(service);
682         }
683         return null;
684         
685     }
686     
687     /* (non-Javadoc)
688      * @see org.apache.cocoon.portal.coplets.basket.BasketManager#getBasketActions()
689      */

690     public List JavaDoc getBasketActions() {
691         return this.basketActions;
692     }
693     
694     /* (non-Javadoc)
695      * @see org.apache.cocoon.portal.coplets.basket.BasketManager#getBriefcaseActions()
696      */

697     public List JavaDoc getBriefcaseActions() {
698         return this.briefcaseActions;
699         }
700         
701     /* (non-Javadoc)
702      * @see org.apache.cocoon.portal.coplets.basket.BasketManager#addBatch(org.apache.cocoon.portal.coplets.basket.ContentItem, int, org.apache.cocoon.portal.coplets.basket.BasketManager.ActionInfo)
703      */

704     public void addBatch(ContentItem item,
705                          int frequencyInDays,
706                          ActionInfo action) {
707         final String JavaDoc name = action.name + "_" + item;
708         
709         final BatchInfo info = new BatchInfo();
710         info.item = item;
711         info.frequencyInSeconds = frequencyInDays * 60 * 60 * 24;
712         info.action = action;
713         if ( frequencyInDays > 0 ) {
714             synchronized (this.batches) {
715                 BatchInfo old = this.searchBatchInfo(item, action);
716                 if ( old != null ) {
717                     this.batches.remove(old);
718                     this.scheduler.removeJob(name);
719                 }
720                 this.batches.add(info);
721             }
722         }
723         final Job job = new Job(action.url, item);
724         
725         try {
726             if ( frequencyInDays > 0) {
727                 this.scheduler.addPeriodicJob(name, job, info.frequencyInSeconds, false, null, null);
728             } else {
729                 this.scheduler.fireJob(job);
730             }
731                 
732         } catch (Exception JavaDoc ignore) {
733             this.getLogger().warn("Exception during adding of new batch.", ignore);
734         }
735     }
736    
737     protected BatchInfo searchBatchInfo(ContentItem item, ActionInfo info) {
738         final Iterator JavaDoc i = this.batches.iterator();
739         while (i.hasNext()) {
740             final BatchInfo current = (BatchInfo)i.next();
741             if ( current.item.equals(item) ) {
742                 if ( current.action.name.equals(info.name) ) {
743                     return current;
744                 }
745             }
746         }
747         return null;
748     }
749     
750     protected static final class BatchInfo {
751         public ContentItem item;
752         public int frequencyInSeconds;
753         public ActionInfo action;
754     }
755     
756     /* (non-Javadoc)
757      * @see org.apache.cocoon.portal.coplets.basket.BasketManager#getBasketAction(java.lang.String)
758      */

759     public ActionInfo getBasketAction(String JavaDoc name) {
760         final Iterator JavaDoc i = this.basketActions.iterator();
761         while ( i.hasNext() ) {
762             final ActionInfo current = (ActionInfo)i.next();
763             if ( current.name.equals(name) ) {
764                 return current;
765             }
766         }
767         return null;
768     }
769     
770     /* (non-Javadoc)
771      * @see org.apache.cocoon.portal.coplets.basket.BasketManager#getBriefcaseAction(java.lang.String)
772      */

773     public ActionInfo getBriefcaseAction(String JavaDoc name) {
774         final Iterator JavaDoc i = this.briefcaseActions.iterator();
775         while ( i.hasNext() ) {
776             final ActionInfo current = (ActionInfo)i.next();
777             if ( current.name.equals(name) ) {
778                 return current;
779             }
780         }
781         return null;
782     }
783     
784     public static final class Job extends ServiceableCronJob implements CronJob {
785         
786         protected final String JavaDoc url;
787         
788         public Job(String JavaDoc url, ContentItem item) {
789             final StringBuffer JavaDoc buffer = new StringBuffer JavaDoc(url);
790             boolean hasParams = url.indexOf('?') != -1;
791             Iterator JavaDoc i = item.attributes.entrySet().iterator();
792             while ( i.hasNext() ) {
793                 final Map.Entry JavaDoc current = (Map.Entry JavaDoc)i.next();
794                 final String JavaDoc key = current.getKey().toString();
795                 if ( !"coplet-attributes".equals(key) ) {
796                     if ( hasParams ) {
797                         buffer.append('&');
798                     } else {
799                         buffer.append('?');
800                         hasParams = true;
801                     }
802                     buffer.append(key);
803                     buffer.append('=');
804                     buffer.append(current.getValue().toString());
805                 }
806             }
807             // now add coplet attributes
808
Map JavaDoc copletAttributes = (Map JavaDoc)item.attributes.get("coplet-attributes");
809             if ( copletAttributes != null ) {
810                 i = copletAttributes.entrySet().iterator();
811                 while ( i.hasNext() ) {
812                     final Map.Entry JavaDoc current = (Map.Entry JavaDoc)i.next();
813                     final String JavaDoc key = current.getKey().toString();
814                     if ( hasParams ) {
815                         buffer.append('&');
816                     } else {
817                         buffer.append('?');
818                         hasParams = true;
819                     }
820                     buffer.append(key);
821                     buffer.append('=');
822                     buffer.append(current.getValue().toString());
823                 }
824             }
825             this.url = buffer.toString();
826         }
827     
828         /* (non-Javadoc)
829          * @see org.apache.cocoon.components.cron.CronJob#execute(java.lang.String)
830          */

831         public void execute(String JavaDoc jobname) {
832             SourceResolver resolver = null;
833             Source source = null;
834             try {
835                 resolver = (SourceResolver) this.manager.lookup(SourceResolver.ROLE);
836                 source = resolver.resolveURI(this.url);
837
838                 InputStreamReader JavaDoc r = new InputStreamReader JavaDoc(source.getInputStream());
839                 try {
840                     char[] b = new char[8192];
841
842                     while( r.read(b) > 0) {
843                         // nothing to do
844
}
845
846                 } finally {
847                     r.close();
848                 }
849             } catch (Exception JavaDoc ignore) {
850                 // we ignore all
851
this.getLogger().warn("Exception during execution of job " + jobname, ignore);
852             } finally {
853                 if ( resolver != null ) {
854                     resolver.release(source);
855                     this.manager.release(resolver);
856                 }
857             }
858         }
859     }
860     
861     
862     /* (non-Javadoc)
863      * @see org.apache.cocoon.portal.coplets.basket.BasketManager#update(org.apache.cocoon.portal.coplets.basket.ContentStore)
864      */

865     public void update(ContentStore store) {
866         this.saveContentStore(store);
867     }
868 }
869
Popular Tags