KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > openedit > modules > cart > XmlProductArchive


1 /*
2  * Created on Oct 3, 2004
3  */

4 package com.openedit.modules.cart;
5
6 import java.io.File JavaDoc;
7 import java.io.FileFilter JavaDoc;
8 import java.io.FileInputStream JavaDoc;
9 import java.io.FileOutputStream JavaDoc;
10 import java.io.IOException JavaDoc;
11 import java.io.InputStreamReader JavaDoc;
12 import java.io.Reader JavaDoc;
13 import java.io.StringWriter JavaDoc;
14 import java.util.ArrayList JavaDoc;
15 import java.util.Iterator JavaDoc;
16 import java.util.List JavaDoc;
17 import java.util.Map JavaDoc;
18 import java.util.Properties JavaDoc;
19
20 import org.apache.commons.collections.map.ReferenceMap;
21 import org.apache.commons.logging.Log;
22 import org.apache.commons.logging.LogFactory;
23 import org.dom4j.Document;
24 import org.dom4j.DocumentException;
25 import org.dom4j.DocumentHelper;
26 import org.dom4j.Element;
27 import org.dom4j.io.SAXReader;
28 import org.openedit.repository.ContentItem;
29 import org.openedit.repository.filesystem.StringItem;
30
31 import com.openedit.OpenEditException;
32 import com.openedit.config.Configuration;
33 import com.openedit.page.Page;
34 import com.openedit.page.PageSettings;
35 import com.openedit.page.manage.PageManager;
36 import com.openedit.store.CatalogArchive;
37 import com.openedit.store.Category;
38 import com.openedit.store.InventoryItem;
39 import com.openedit.store.Product;
40 import com.openedit.store.ProductArchive;
41 import com.openedit.store.ProductPathFinder;
42 import com.openedit.store.Store;
43 import com.openedit.store.StoreException;
44 import com.openedit.store.Types;
45 import com.openedit.store.products.PropertyDetails;
46 import com.openedit.util.FileUtils;
47 import com.openedit.util.PathUtilities;
48 import com.openedit.util.XmlUtil;
49
50 /**
51  * A product archive that stores the data about each product in an
52  * <tt>.xconf</tt> file in the <tt>storehome/products</tt> directory (as
53  * determined by its {@link ProductPathFinder}).
54  *
55  * @author cburkey
56  */

57 public class XmlProductArchive extends BaseXmlArchive implements ProductArchive
58 {
59     private static final Log log = LogFactory.getLog(XmlProductArchive.class);
60
61     protected Map JavaDoc fieldProducts;
62     protected PageManager fieldPageManager;
63     // protected ProductPathFinder fieldProductPathFinder;
64
protected PropertyDetails fieldPropertyDetails;
65     protected Store fieldStore;
66     protected XmlUtil fieldXmlUtil;
67     protected boolean fieldUpdateExistingRecord = true;
68
69     public XmlProductArchive()
70     {
71         log.debug("Created archive");
72     }
73
74     protected Map JavaDoc getProducts()
75     {
76         if (fieldProducts == null)
77         {
78             // HARD means even if the object goes out of scope we still keep it
79
// in the hashmap
80
// until the memory runs low then things get dumped randomly
81
fieldProducts = new ReferenceMap(ReferenceMap.HARD, ReferenceMap.HARD);
82             // fieldProducts = new HashMap();
83
}
84         return fieldProducts;
85     }
86
87     /*
88      * (non-javadoc)
89      *
90      * @see com.openedit.store.ItemLoader#clearItems()
91      */

92     public void clearProducts()
93     {
94         getPageManager().clearCache();
95         // fieldProducts = null;
96
}
97
98     public void deleteProduct(Product inProduct) throws StoreException
99     {
100         getProducts().remove(inProduct.getId());
101         try
102         {
103             Page page = getPageManager().getPage(buildItemUrl(inProduct.getId()));
104             getPageManager().removePage(page);
105         }
106         catch (Exception JavaDoc ex)
107         {
108             throw new StoreException(ex);
109         }
110     }
111
112     public void clearProduct(Product inProduct)
113     {
114         if (inProduct != null)
115         {
116             getProducts().remove(inProduct.getId());
117             getPageManager().clearCache(buildItemUrl(inProduct.getId()));
118         }
119     }
120
121     /*
122      * (non-javadoc)
123      *
124      * @see com.openedit.store.ItemLoader#loadItem(java.lang.String)
125      */

126     public Product getProduct(String JavaDoc inId) throws StoreException
127     {
128         if (inId == null)
129         {
130             return null;
131         }
132         Product item = (Product) getProducts().get(inId);
133         if (item == null)
134         {
135             item = new Product();
136             String JavaDoc url = buildItemUrl(inId);
137             log.debug("Loading " + url);
138             try
139             {
140                 if (populateProduct(item, url))
141                 {
142                     getProducts().put(inId, item);
143                 }
144                 else
145                 {
146                     log.error("No Such product " + url);
147                     return null;
148                 }
149             }
150             catch (OpenEditException e)
151             {
152                 throw new StoreException(e);
153             }
154         }
155         return item;
156     }
157
158     protected String JavaDoc buildItemUrl(String JavaDoc inId)
159     {
160         String JavaDoc catalogId = getStore().getCatalogId();
161         String JavaDoc idToPath = getProductPathFinder().idToPath(inId);
162         String JavaDoc url = "/" + catalogId + "/products/" + idToPath + ".html";
163         return url;
164     }
165
166     protected boolean populateProduct(Product inProduct, String JavaDoc url) throws OpenEditException, StoreException
167     {
168         // Speed up: Just open the xconf with XmlConfiguration
169
Page productPage = getPageManager().getPage(url);
170         // if (!productPage.exists())
171
// {
172
// return false;
173
// }
174
Configuration config = productPage.getPageSettings().getUserDefinedData();
175         if (config == null)
176         {
177             return false;
178         }
179         Configuration productConfig = config.getChild("product");
180         if (productConfig == null)
181         {
182             return false;
183         }
184         String JavaDoc name = productConfig.getAttribute("name");
185         inProduct.setName(name);
186
187         String JavaDoc order = productConfig.getAttribute("ordering");
188         if (order != null && order.length() > 0)
189         {
190             inProduct.setOrdering(Integer.parseInt(order));
191         }
192
193         inProduct.setAvailable(true);
194         String JavaDoc avail = productConfig.getAttribute("available");
195         if (avail != null)
196         {
197             inProduct.setAvailable(Boolean.parseBoolean(avail));
198         }
199         inProduct.setId(productConfig.getAttribute("id"));
200         loadCatalogs(inProduct, productConfig);
201         inProduct.setPriceSupport(createPriceSupport(productConfig));
202         inProduct.setKeywords(productConfig.getChildValue("keywords"));
203
204         Configuration type = productConfig.getChild("delivery-type");
205         if (type != null)
206         {
207             inProduct.setDeliveryType(type.getAttribute("name"));
208         }
209
210         String JavaDoc taxExempt = productConfig.getAttribute("taxExempt");
211         if (taxExempt != null)
212         {
213             inProduct.setTaxExempt(Boolean.valueOf(taxExempt).booleanValue());
214         }
215         else
216         {
217             inProduct.setTaxExempt(false);
218         }
219
220         loadInventoryItems(inProduct, productConfig);
221
222         for (Iterator JavaDoc iter = productConfig.getChildren("property").iterator(); iter.hasNext();)
223         {
224             Configuration propConfig = (Configuration) iter.next();
225             inProduct.addProperty(propConfig.getAttribute("name"), propConfig.getValue());
226         }
227
228         Configuration dep = productConfig.getChild("department");
229         if (dep != null)
230         {
231             String JavaDoc depid = dep.getAttribute("id");
232             inProduct.setDepartment(depid);
233         }
234
235         Configuration handlingChargeLevel = productConfig.getChild("handling-charge-level");
236         if (handlingChargeLevel != null)
237         {
238             inProduct.setHandlingChargeLevel(handlingChargeLevel.getValue());
239         }
240         else
241         {
242             inProduct.setHandlingChargeLevel(null);
243         }
244
245         loadShippingMethod(inProduct, productConfig);
246
247         Configuration customPrice = productConfig.getChild("custom-price");
248         if (customPrice != null)
249         {
250             inProduct.setCustomPrice("true".equalsIgnoreCase(customPrice.getValue()));
251         }
252         else
253         {
254             inProduct.setCustomPrice(false);
255         }
256
257         loadOptions(inProduct, productConfig);
258
259         loadRelatedProductIds(inProduct, productConfig);
260
261         return true;
262     }
263
264     protected void loadInventoryItems(Product inProduct, Configuration inProductConfig)
265     {
266         inProduct.clearItems();
267         for (Iterator JavaDoc iter = inProductConfig.getChildren("item").iterator(); iter.hasNext();)
268         {
269             Configuration itemConfig = (Configuration) iter.next();
270             InventoryItem currentItem = createInventoryItem(itemConfig, inProduct);
271             inProduct.addInventoryItem(currentItem);
272         }
273     }
274
275     protected void loadShippingMethod(Product inProduct, Configuration inProductConfig)
276     {
277         Configuration shipping = inProductConfig.getChild("shipping-method");
278         if (shipping != null)
279         {
280             String JavaDoc id = shipping.getAttribute("id");
281             inProduct.setShippingMethodId(id);
282         }
283     }
284
285     protected void loadOptions(Product inProduct, Configuration inProductConfig)
286     {
287         inProduct.clearOptions();
288         for (Iterator JavaDoc iter = inProductConfig.getChildren("option").iterator(); iter.hasNext();)
289         {
290             Configuration optionConfig = (Configuration) iter.next();
291             inProduct.addOption(createOption(optionConfig));
292         }
293     }
294
295     protected void loadOptions(InventoryItem inItem, Configuration inProductConfig)
296     {
297         for (Iterator JavaDoc iter = inProductConfig.getChildren("option").iterator(); iter.hasNext();)
298         {
299             Configuration optionConfig = (Configuration) iter.next();
300             inItem.addOption(createOption(optionConfig));
301         }
302     }
303
304     protected void loadRelatedProductIds(Product inProduct, Configuration inProductConfig)
305     {
306         inProduct.clearRelatedProductIds();
307         Configuration relatedProductsElem = inProductConfig.getChild("related-products");
308         if (relatedProductsElem != null)
309         {
310             for (Iterator JavaDoc iter = relatedProductsElem.getChildIterator("product"); iter.hasNext();)
311             {
312                 Configuration relatedProdConfig = (Configuration) iter.next();
313                 inProduct.addRelatedProductId(relatedProdConfig.getAttribute("id"));
314             }
315         }
316     }
317
318     /*
319      * (non-javadoc)
320      *
321      * @see com.openedit.store.ItemLoader#saveProduct(com.openedit.store.Product)
322      */

323     public void saveProduct(Product inProduct) throws StoreException
324     {
325         try
326         {
327             // TODO: Speed check this section
328
String JavaDoc url = buildItemUrl(inProduct.getId());
329             Document document = null;
330             String JavaDoc path = getPageManager().getPageSettingsManager().toXconfPath(url);
331             String JavaDoc encoding = "UTF-8";
332             if (isUpdateExistingRecord())
333             {
334                 // Page encode = getPageManager().getPage("/" +
335
// getStore().getCatalogId() + "/products/index.html");
336
// encoding = encode.getCharacterEncoding();
337
document = loadXconfDocument(path, encoding);
338                 Element productelm = document.getRootElement().element("product");
339                 // remove old products
340
if (productelm != null)
341                 {
342                     document.getRootElement().remove(productelm);
343                 }
344             }
345             else
346             {
347                 document = DocumentHelper.createDocument();
348                 document.setRootElement(DocumentHelper.createElement("page"));
349             }
350             Element rootElement = document.getRootElement();
351             saveProduct(inProduct, rootElement);
352             // save it to disk
353
StringWriter JavaDoc output = new StringWriter JavaDoc();
354             getXmlUtil().saveXml(document, output, encoding);
355
356             StringItem xconf = new StringItem(path, output.toString(), encoding);
357             xconf.setMakeVersion(false);
358
359             getPageManager().getPageSettingsManager().saveSetting(xconf);
360
361             String JavaDoc id = inProduct.getId();
362             getProducts().put(id, inProduct);
363
364         }
365         catch (Exception JavaDoc ex)
366         {
367             log.error(ex);
368             throw ex instanceof StoreException ? (StoreException) ex : new StoreException(ex);
369         }
370     }
371
372     public void saveProduct(Product inProduct, Element rootElement)
373     {
374         Element productelm = rootElement.addElement("product");
375         saveProductAttributes(inProduct, productelm);
376
377         deleteElements(productelm, "item");
378         // save items
379
for (Iterator JavaDoc iter = inProduct.getInventoryItems().iterator(); iter.hasNext();)
380         {
381             InventoryItem inventory = (InventoryItem) iter.next();
382             saveItem(productelm, inventory);
383         }
384
385         // save out catalogs
386
saveProductCatalogs(inProduct, productelm);
387
388         saveProductPricing(inProduct, productelm);
389
390 // if (inProduct.getKeywords() != null && !hasProperty(rootElement, "keywords"))
391
// {
392
// // copy keywords to page property
393
// Element pageprop = rootElement.addElement("property");
394
// pageprop.addAttribute("name", "keywords");
395
// pageprop.setText(inProduct.getKeywords());
396
// }
397
if (inProduct.getDeliveryType() != null)
398         {
399             Element type = productelm.addElement("delivery-type");
400             type.addAttribute("name", inProduct.getDeliveryType());
401         }
402         // clear out any old product properties
403
deleteElements(productelm, "property");
404         // saves out properties
405
for (Iterator JavaDoc iter = inProduct.getProperties().keySet().iterator(); iter.hasNext();)
406         {
407             String JavaDoc key = (String JavaDoc) iter.next();
408             Element newProperty = productelm.addElement("property");
409             newProperty.addAttribute("name", key);
410             newProperty.setText(inProduct.get(key));
411         }
412
413         saveOptions(inProduct.getOptions(), productelm);
414
415         saveRelatedProducts(inProduct, productelm);
416
417     }
418
419     protected boolean hasProperty(Element inRootElement, String JavaDoc inName)
420     {
421         for (Iterator JavaDoc iter = inRootElement.elementIterator("property"); iter.hasNext();)
422         {
423             Element element = (Element) iter.next();
424             String JavaDoc name = element.attributeValue("name");
425             if (inName.equals(name))
426             {
427                 return true;
428             }
429         }
430         return false;
431     }
432
433     private Document loadXconfDocument(String JavaDoc inPath, String JavaDoc encode) throws OpenEditException, DocumentException, IOException JavaDoc
434     {
435         Document document;
436
437         // String url = PRODUCTS_URL_PATH + "/" +
438
// getProductPathFinder().idToPath(inId) + ".html";
439

440         ContentItem item = getPageManager().getPageSettingsManager().getRepository().get(inPath);
441
442         if (item.exists())
443         {
444             SAXReader xmlreader = getXmlUtil().getReader();
445             Reader JavaDoc reader = new InputStreamReader JavaDoc(item.getInputStream(), encode);
446             try
447             {
448                 document = xmlreader.read(reader);
449             }
450             finally
451             {
452                 FileUtils.safeClose(reader);
453             }
454         }
455         else
456         {
457             document = DocumentHelper.createDocument();
458             document.setRootElement(DocumentHelper.createElement("page"));
459         }
460         return document;
461     }
462
463     protected void saveProductAttributes(Product inProduct, Element productelm)
464     {
465         String JavaDoc name = inProduct.getName();
466         // name = SpecialCharacter.escapeSpecialCharacters(name);
467
productelm.addAttribute("name", name);
468         productelm.addAttribute("id", inProduct.getId());
469         if( inProduct.getOrdering() > 0)
470         {
471             productelm.addAttribute("ordering", String.valueOf(inProduct.getOrdering()));
472         }
473         saveKeywords(inProduct, productelm);
474         // set availability
475
if ( !inProduct.isAvailable())
476         {
477             productelm.addAttribute("available", "false");
478         }
479     }
480
481     protected void saveProductPricing(Product inProduct, Element productelm)
482     {
483         if (inProduct.hasProductLevelPricing())
484         {
485             addPrice(productelm, inProduct.getPriceSupport());
486         }
487
488         if (inProduct.isTaxExempt())
489         {
490             productelm.addAttribute("taxExempt", String.valueOf(inProduct.isTaxExempt()));
491         }
492         if (inProduct.isCustomPrice())
493         {
494             Element customPriceElem = productelm.addElement("custom-price");
495             customPriceElem.setText(String.valueOf(inProduct.isCustomPrice()));
496         }
497
498         // handling charge level
499
deleteElements(productelm, "handling-charge-level");
500         if (inProduct.getHandlingChargeLevel() != null)
501         {
502             Element handlingChargeElem = productelm.addElement("handling-charge-level");
503             handlingChargeElem.setText(inProduct.getHandlingChargeLevel());
504         }
505         deleteElements(productelm, "shipping-method");
506         if (inProduct.getShippingMethodId() != null)
507         {
508             // we only support fixed costs methods for products
509
Element shipping = productelm.addElement("shipping-method");
510             shipping.addAttribute("id", inProduct.getShippingMethodId());
511         }
512
513     }
514
515     protected void saveKeywords(Product inProduct, Element inProductElment)
516     {
517         if (inProduct.getKeywords() != null)
518         {
519             deleteElements(inProductElment, "keywords");
520             Element keywordElement = inProductElment.addElement("keywords");
521             keywordElement.setText(inProduct.getKeywords());
522         }
523     }
524
525     /**
526      * @param inProduct
527      * @param productelm
528      */

529     private void saveProductCatalogs(Product inProduct, Element productelm)
530     {
531         // remove old catalogs
532
deleteElements(productelm, "category");
533         deleteElements(productelm, "catalog"); // TODO: Remove this line in 6.0
534
// TODO: Save over the old category
535
for (Iterator JavaDoc iter = inProduct.getCatalogs().iterator(); iter.hasNext();)
536         {
537             Category catalog = (Category) iter.next();
538             Element cat = productelm.addElement("category");
539             cat.addAttribute("id", catalog.getId());
540             if (catalog.isUserSelected())
541             {
542                 cat.addAttribute("userselected", "true");
543             }
544             if (catalog == inProduct.getDefaultCatalog())
545             {
546                 cat.addAttribute("default", "true");
547             }
548         }
549     }
550
551     protected void saveRelatedProducts(Product inProduct, Element inProductElement)
552     {
553         deleteElements(inProductElement, "related-products");
554         if (inProduct.getRelatedProductIds() != null)
555         {
556             Element relatedProductsElem = inProductElement.addElement("related-products");
557             for (Iterator JavaDoc iter = inProduct.getRelatedProductIds().iterator(); iter.hasNext();)
558             {
559                 String JavaDoc relatedProductId = (String JavaDoc) iter.next();
560                 relatedProductsElem.addElement("product").addAttribute("id", relatedProductId);
561             }
562         }
563     }
564
565     protected void loadCatalogs(Product inProduct, Configuration inProductConfig) throws StoreException
566     {
567         inProduct.clearCatalogs();
568         // TODO: Remove this next chunk of code as duplicate
569
for (Iterator JavaDoc iter = inProductConfig.getChildren("catalog").iterator(); iter.hasNext();) // TODO:
570
// This
571
// is
572
// Deprecated!
573
// Should
574
// be
575
// removed
576
// in OE 6.0
577
{
578             Configuration catalogconfig = (Configuration) iter.next();
579             String JavaDoc catid = catalogconfig.getAttribute("id");
580             Category catalog = getCatalogArchive().getCatalog(catid);
581             if (catalog == null)
582             {
583                 // The reason we do not throw this exception is some sites
584
// need more flexability. TODO: Add a boolean for
585
// strict=true|false
586
// to this object
587
// throw new StoreException("No such catalog " + catid);
588
log.error("Could not find a catalog named: " + catid);
589
590                 continue;
591             }
592             String JavaDoc defaultCatalog = catalogconfig.getAttribute("default");
593             if ("true".equalsIgnoreCase(defaultCatalog))
594             {
595                 inProduct.setDefaultCatalog(catalog);
596             }
597
598             inProduct.addCatalog(catalog);
599         }
600         // TODO: End Deprecation
601

602         for (Iterator JavaDoc iter = inProductConfig.getChildren("category").iterator(); iter.hasNext();)
603         {
604             Configuration catalogconfig = (Configuration) iter.next();
605             String JavaDoc catid = catalogconfig.getAttribute("id");
606             Category catalog = getCatalogArchive().getCatalog(catid);
607             if (catalog == null)
608             {
609                 // The reason we do not throw this exception is some sites
610
// need more flexability. TODO: Add a boolean for
611
// strict=true|false
612
// to this object
613
// throw new StoreException("No such catalog " + catid);
614
log.error("Could not find a catalog named: " + catid);
615
616                 continue;
617             }
618             String JavaDoc defaultCatalog = catalogconfig.getAttribute("default");
619             if ("true".equalsIgnoreCase(defaultCatalog))
620             {
621                 inProduct.setDefaultCatalog(catalog);
622             }
623             inProduct.addCatalog(catalog);
624         }
625     }
626
627     public PageManager getPageManager()
628     {
629         return fieldPageManager;
630     }
631
632     public void setPageManager(PageManager inPageManager)
633     {
634         fieldPageManager = inPageManager;
635     }
636
637     protected InventoryItem createInventoryItem(Configuration inItemConfig, Product inProduct)
638     {
639         InventoryItem currentItem = new InventoryItem();
640         currentItem.setProduct(inProduct);
641         String JavaDoc inventory = inItemConfig.getAttribute("inventory");
642         currentItem.setQuantityInStock(Integer.parseInt(inventory));
643         String JavaDoc sku = inItemConfig.getAttribute("sku");
644         currentItem.setSku(sku);
645
646         String JavaDoc backordered = inItemConfig.getAttribute("backordered");
647         if (backordered != null && Boolean.parseBoolean(backordered))
648         {
649             currentItem.setBackOrdered(true);
650         }
651
652         currentItem.setDescription(inItemConfig.getAttribute("description"));
653
654         // Deprecated. We now use options and properties for everything
655
Configuration sizeConfig = inItemConfig.getChild("size");
656         if (sizeConfig != null)
657         {
658             String JavaDoc sizeId = sizeConfig.getAttribute("id");
659             if (sizeId != null)
660             {
661                 currentItem.setSize(sizeId);
662             }
663         }
664         Configuration colorConfig = inItemConfig.getChild("color");
665         if (colorConfig != null)
666         {
667             String JavaDoc colorId = colorConfig.getAttribute("id");
668             if (colorId != null)
669             {
670                 currentItem.setColor(colorId);
671             }
672         }
673         Configuration weightConfig = inItemConfig.getChild("weight");
674         if (weightConfig != null)
675         {
676             String JavaDoc weight = weightConfig.getAttribute("value");
677             if (weight != null && weight.length() > 0)
678             {
679                 currentItem.setWeight(Double.parseDouble(weight));
680             }
681         }
682         currentItem.setPriceSupport(createPriceSupport(inItemConfig));
683
684         // load up the properties
685
for (Iterator JavaDoc iter = inItemConfig.getChildren("property").iterator(); iter.hasNext();)
686         {
687             Configuration propConfig = (Configuration) iter.next();
688             currentItem.addProperty(propConfig.getAttribute("name"), propConfig.getValue());
689         }
690         loadOptions(currentItem, inItemConfig);
691         return currentItem;
692     }
693
694     protected void saveItem(Element inProductElem, InventoryItem inInventoryItem)
695     {
696         Element ielement = inProductElem.addElement("item");
697
698         if (inInventoryItem.isBackOrdered())
699         {
700             ielement.addAttribute("backordered", "true");
701         }
702         ielement.addAttribute("sku", inInventoryItem.getSku());
703         ielement.addAttribute("inventory", String.valueOf(inInventoryItem.getQuantityInStock()));
704         if (inInventoryItem.getDescription() != null)
705         {
706             ielement.addAttribute("description", inInventoryItem.getDescription());
707         }
708         // ielement.addElement("color").addAttribute("id",
709
// inInventoryItem.getColor());
710
// String size = inInventoryItem.getSize();
711
// ielement.addElement("size").addAttribute("id", size);
712
double weight = inInventoryItem.getWeight();
713         ielement.addElement("weight").addAttribute("value", String.valueOf(weight));
714         saveOptions(inInventoryItem.getOptions(), ielement);
715
716         // Output something that looks like:
717
// <price quantity="1">19.95</price>
718
if (inInventoryItem.hasOwnPrice())
719         {
720             addPrice(ielement, inInventoryItem.getPriceSupport());
721         }
722         // save properties
723
for (Iterator JavaDoc iter = inInventoryItem.getProperties().keySet().iterator(); iter.hasNext();)
724         {
725             String JavaDoc key = (String JavaDoc) iter.next();
726             Element newProperty = ielement.addElement("property");
727             newProperty.addAttribute("name", key);
728             newProperty.setText(inInventoryItem.get(key));
729         }
730
731     }
732
733     protected CatalogArchive getCatalogArchive()
734     {
735         return getStore().getCatalogArchive();
736     }
737
738     /*
739      * (non-javadoc)
740      *
741      * @see com.openedit.store.ProductArchive#loadDescription(com.openedit.store.Product)
742      */

743     public String JavaDoc loadDescription(Product inProduct) throws StoreException
744     {
745         String JavaDoc url = buildItemUrl(inProduct.getId());
746         try
747         {
748             Page page = getPageManager().getPage(url);
749             if (page.exists())
750             {
751                 String JavaDoc content = page.getContent();
752                 return content;
753             }
754             return null;
755         }
756         catch (Exception JavaDoc ex)
757         {
758             throw new StoreException(ex);
759         }
760     }
761
762     // gets the next product ID if needed
763
public synchronized String JavaDoc nextProductNumber(Store inStore) throws StoreException
764     {
765         FileInputStream JavaDoc inStream = null;
766         FileOutputStream JavaDoc outStream = null;
767         try
768         {
769             File JavaDoc productProperties = new File JavaDoc(inStore.getStoreDirectory(), "configuration/product.properties");
770             Properties JavaDoc props = new Properties JavaDoc();
771             if (productProperties.exists())
772             {
773                 inStream = new FileInputStream JavaDoc(productProperties);
774                 props.load(inStream);
775             }
776             final String JavaDoc COUNT_PROPERTY = "productIdCount";
777             String JavaDoc countString = props.getProperty(COUNT_PROPERTY);
778             int count = 100;
779             if (countString != null)
780             {
781                 count = Integer.valueOf(countString).intValue();
782             }
783             count++;
784             countString = String.valueOf(count);
785             props.setProperty(COUNT_PROPERTY, countString);
786             outStream = new FileOutputStream JavaDoc(productProperties);
787             props.store(outStream, "");
788             return countString;
789         }
790         catch (Exception JavaDoc ex)
791         {
792             throw new StoreException(ex);
793         }
794         finally
795         {
796             try
797             {
798                 if (outStream != null)
799                 {
800                     outStream.close();
801                 }
802                 if (inStream != null)
803                 {
804                     inStream.close();
805                 }
806             }
807             catch (Exception JavaDoc ex)
808             {
809                 // do nothing
810
}
811         }
812     }
813
814     /*
815      * (non-javadoc)
816      *
817      * @see com.openedit.store.ProductArchive#saveProductDescription(com.openedit.store.Product)
818      */

819     public void saveProductDescription(Product inProduct, String JavaDoc inDescription) throws StoreException
820     {
821         if (inDescription == null)
822         {
823             return;
824         }
825         String JavaDoc url = buildItemUrl(inProduct.getId());
826         try
827         {
828             Page page = getPageManager().getPage(url);
829             StringItem item = new StringItem(page.getPath(), inDescription, page.getCharacterEncoding());
830             item.setMakeVersion(false);
831             getPageManager().getRepository().put(item);
832         }
833         catch (Exception JavaDoc ex)
834         {
835             throw new StoreException(ex);
836         }
837     }
838
839     public void saveBlankProductDescription(Product inProduct) throws StoreException
840     {
841         String JavaDoc url = buildItemUrl(inProduct.getId());
842         try
843         {
844             Page page = getPageManager().getPage(url);
845             if (page.exists())
846             {
847                 return;
848             }
849             String JavaDoc desc = inProduct.getDescription();
850             if (desc == null)
851             {
852                 desc = "no description available";
853             }
854             StringItem item = new StringItem(page.getPath(), desc, page.getCharacterEncoding());
855             item.setMakeVersion(false);
856             page.setContentItem(item);
857             getPageManager().putPage(page);
858         }
859         catch (Exception JavaDoc ex)
860         {
861             throw new StoreException(ex);
862         }
863     }
864
865     public ProductPathFinder getProductPathFinder()
866     {
867         return getStore().getProductPathFinder();
868     }
869
870     public PropertyDetails getPropertyDetails() throws StoreException
871     {
872         try
873         {
874             Page page = getPageManager().getPage("/" + getStore().getCatalogId() + "/configuration/productproperties.xml");
875             if (fieldPropertyDetails != null && page.exists() && fieldPropertyDetails.getLastLoaded() != page.getLastModified().getTime())
876             {
877                 fieldPropertyDetails = null;
878             }
879             if (fieldPropertyDetails == null)
880             {
881                 fieldPropertyDetails = new PropertyDetails();
882                 if (page.exists())
883                 {
884                     fieldPropertyDetails.addAllDetails(page.getReader());
885                     fieldPropertyDetails.setLastLoaded(page.getLastModified().getTime());
886                 }
887             }
888         }
889         catch (Exception JavaDoc ex)
890         {
891             throw new StoreException(ex);
892         }
893         return fieldPropertyDetails;
894     }
895
896     public List JavaDoc listAllProductIds()
897     {
898         List JavaDoc all = new ArrayList JavaDoc(500);
899
900         FileFilter JavaDoc filter = new FileFilter JavaDoc()
901         {
902             public boolean accept(File JavaDoc inDir)
903             {
904                 String JavaDoc inName = inDir.getName();
905                 if (inDir.isDirectory() || inName.endsWith(".xconf"))
906                 {
907                     if (!inName.endsWith("_site.xconf") && !inName.endsWith("_default.xconf") && !inName.equals(".xconf"))
908                     {
909                         return true;
910                     }
911                 }
912                 return false;
913             }
914         };
915         File JavaDoc dir = new File JavaDoc(getStoreDirectory(), "products/");
916         if (dir.exists())
917         {
918             findFiles(dir, all, filter);
919         }
920
921         return all;
922     }
923
924     protected void findFiles(File JavaDoc inSearchDirectory, List JavaDoc inAll, FileFilter JavaDoc inFilter)
925     {
926         File JavaDoc[] toadd = inSearchDirectory.listFiles(inFilter);
927         if (toadd != null)
928         {
929             for (int i = 0; i < toadd.length; i++)
930             {
931                 File JavaDoc file = toadd[i];
932                 if (file.isDirectory())
933                 {
934                     findFiles(file, inAll, inFilter);
935                 }
936                 else
937                 {
938                     String JavaDoc id = PathUtilities.extractPageName(file.getName());
939                     inAll.add(id);
940                 }
941             }
942         }
943     }
944
945     public Store getStore()
946     {
947         return fieldStore;
948     }
949
950     public void setStore(Store inStore)
951     {
952         fieldStore = inStore;
953     }
954
955     public File JavaDoc getStoreDirectory()
956     {
957         return getStore().getStoreDirectory();
958     }
959
960     public XmlUtil getXmlUtil()
961     {
962         if (fieldXmlUtil == null)
963         {
964             fieldXmlUtil = new XmlUtil();
965         }
966         return fieldXmlUtil;
967     }
968
969     public boolean isUpdateExistingRecord()
970     {
971         return fieldUpdateExistingRecord;
972     }
973
974     public void setUpdateExistingRecord(boolean inUpdateExistingRecord)
975     {
976         fieldUpdateExistingRecord = inUpdateExistingRecord;
977     }
978
979 }
980
Popular Tags