1   /**
2    * Copyright (c) 2000-2007 Liferay, Inc. All rights reserved.
3    *
4    * Permission is hereby granted, free of charge, to any person obtaining a copy
5    * of this software and associated documentation files (the "Software"), to deal
6    * in the Software without restriction, including without limitation the rights
7    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8    * copies of the Software, and to permit persons to whom the Software is
9    * furnished to do so, subject to the following conditions:
10   *
11   * The above copyright notice and this permission notice shall be included in
12   * all copies or substantial portions of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
22  
23  package com.liferay.portlet.shopping.service.impl;
24  
25  import com.liferay.counter.service.CounterLocalServiceUtil;
26  import com.liferay.portal.PortalException;
27  import com.liferay.portal.SystemException;
28  import com.liferay.portal.kernel.util.GetterUtil;
29  import com.liferay.portal.kernel.util.OrderByComparator;
30  import com.liferay.portal.kernel.util.StringPool;
31  import com.liferay.portal.kernel.util.StringUtil;
32  import com.liferay.portal.kernel.util.Validator;
33  import com.liferay.portal.model.User;
34  import com.liferay.portal.model.impl.ResourceImpl;
35  import com.liferay.portal.service.ResourceLocalServiceUtil;
36  import com.liferay.portal.service.impl.ImageLocalUtil;
37  import com.liferay.portal.service.persistence.UserUtil;
38  import com.liferay.portal.util.PropsUtil;
39  import com.liferay.portlet.amazonrankings.model.AmazonRankings;
40  import com.liferay.portlet.amazonrankings.util.AmazonRankingsUtil;
41  import com.liferay.portlet.shopping.DuplicateItemSKUException;
42  import com.liferay.portlet.shopping.ItemLargeImageNameException;
43  import com.liferay.portlet.shopping.ItemLargeImageSizeException;
44  import com.liferay.portlet.shopping.ItemMediumImageNameException;
45  import com.liferay.portlet.shopping.ItemMediumImageSizeException;
46  import com.liferay.portlet.shopping.ItemNameException;
47  import com.liferay.portlet.shopping.ItemSKUException;
48  import com.liferay.portlet.shopping.ItemSmallImageNameException;
49  import com.liferay.portlet.shopping.ItemSmallImageSizeException;
50  import com.liferay.portlet.shopping.NoSuchItemException;
51  import com.liferay.portlet.shopping.model.ShoppingCategory;
52  import com.liferay.portlet.shopping.model.ShoppingItem;
53  import com.liferay.portlet.shopping.model.ShoppingItemField;
54  import com.liferay.portlet.shopping.model.ShoppingItemPrice;
55  import com.liferay.portlet.shopping.model.impl.ShoppingItemPriceImpl;
56  import com.liferay.portlet.shopping.service.base.ShoppingItemLocalServiceBaseImpl;
57  import com.liferay.portlet.shopping.service.persistence.ShoppingCategoryUtil;
58  import com.liferay.portlet.shopping.service.persistence.ShoppingItemFieldUtil;
59  import com.liferay.portlet.shopping.service.persistence.ShoppingItemFinder;
60  import com.liferay.portlet.shopping.service.persistence.ShoppingItemPriceUtil;
61  import com.liferay.portlet.shopping.service.persistence.ShoppingItemUtil;
62  import com.liferay.util.FileUtil;
63  import com.liferay.util.Http;
64  import com.liferay.util.PwdGenerator;
65  import com.liferay.util.SystemProperties;
66  
67  import java.io.File;
68  import java.io.FileOutputStream;
69  import java.io.IOException;
70  import java.io.OutputStream;
71  
72  import java.util.ArrayList;
73  import java.util.Date;
74  import java.util.Iterator;
75  import java.util.List;
76  
77  /**
78   * <a href="ShoppingItemLocalServiceImpl.java.html"><b><i>View Source</i></b>
79   * </a>
80   *
81   * @author Brian Wing Shun Chan
82   *
83   */
84  public class ShoppingItemLocalServiceImpl
85      extends ShoppingItemLocalServiceBaseImpl {
86  
87      public void addBookItems(long userId, long categoryId, String[] isbns)
88          throws PortalException, SystemException {
89  
90          try {
91              String tmpDir = SystemProperties.get(SystemProperties.TMP_DIR);
92  
93              for (int i = 0; (i < isbns.length) && (i < 50); i++) {
94                  String isbn = isbns[i];
95  
96                  AmazonRankings amazonRankings =
97                      AmazonRankingsUtil.getAmazonRankings(isbn);
98  
99                  if (amazonRankings == null) {
100                     continue;
101                 }
102 
103                 String name = amazonRankings.getProductName();
104                 String description = StringPool.BLANK;
105                 String properties = getBookProperties(amazonRankings);
106 
107                 int minQuantity = 0;
108                 int maxQuantity = 0;
109                 double price = amazonRankings.getListPrice();
110                 double discount = 1 - amazonRankings.getOurPrice() / price;
111                 boolean taxable = true;
112                 double shipping = 0.0;
113                 boolean useShippingFormula = true;
114 
115                 ShoppingItemPrice itemPrice = ShoppingItemPriceUtil.create(0);
116 
117                 itemPrice.setMinQuantity(minQuantity);
118                 itemPrice.setMaxQuantity(maxQuantity);
119                 itemPrice.setPrice(price);
120                 itemPrice.setDiscount(discount);
121                 itemPrice.setTaxable(taxable);
122                 itemPrice.setShipping(shipping);
123                 itemPrice.setUseShippingFormula(useShippingFormula);
124                 itemPrice.setStatus(
125                     ShoppingItemPriceImpl.STATUS_ACTIVE_DEFAULT);
126 
127                 boolean requiresShipping = true;
128                 int stockQuantity = 0;
129                 boolean featured = false;
130                 Boolean sale = null;
131 
132                 // Small image
133 
134                 boolean smallImage = true;
135                 String smallImageURL = StringPool.BLANK;
136                 File smallFile = new File(
137                     tmpDir + File.separatorChar +
138                     PwdGenerator.getPassword(
139                         PwdGenerator.KEY1 + PwdGenerator.KEY2, 12) + ".jpg");
140 
141                 byte[] smallBytes = Http.URLtoByteArray(
142                     amazonRankings.getSmallImageURL());
143 
144                 if (smallBytes.length < 1024) {
145                     smallImage = false;
146                 }
147                 else {
148                     OutputStream out = new FileOutputStream(smallFile);
149                     out.write(smallBytes);
150                     out.close();
151                 }
152 
153                 // Medium image
154 
155                 boolean mediumImage = true;
156                 String mediumImageURL = StringPool.BLANK;
157                 File mediumFile = new File(
158                     tmpDir + File.separatorChar +
159                     PwdGenerator.getPassword(
160                         PwdGenerator.KEY1 + PwdGenerator.KEY2, 12) + ".jpg");
161 
162                 byte[] mediumBytes = Http.URLtoByteArray(
163                     amazonRankings.getMediumImageURL());
164 
165                 if (mediumBytes.length < 1024) {
166                     mediumImage = false;
167                 }
168                 else {
169                     OutputStream out = new FileOutputStream(mediumFile);
170                     out.write(mediumBytes);
171                     out.close();
172                 }
173 
174                 // Large image
175 
176                 boolean largeImage = true;
177                 String largeImageURL = StringPool.BLANK;
178                 File largeFile = new File(
179                     tmpDir + File.separatorChar +
180                     PwdGenerator.getPassword(
181                         PwdGenerator.KEY1 + PwdGenerator.KEY2, 12) + ".jpg");
182 
183                 byte[] largeBytes = Http.URLtoByteArray(
184                     amazonRankings.getLargeImageURL());
185 
186                 if (largeBytes.length < 1024) {
187                     largeImage = false;
188                 }
189                 else {
190                     OutputStream out = new FileOutputStream(largeFile);
191                     out.write(largeBytes);
192                     out.close();
193                 }
194 
195                 List itemFields = new ArrayList();
196 
197                 List itemPrices = new ArrayList();
198 
199                 itemPrices.add(itemPrice);
200 
201                 boolean addCommunityPermissions = true;
202                 boolean addGuestPermissions = true;
203 
204                 addItem(
205                     userId, categoryId, isbn, name, description, properties,
206                     StringPool.BLANK, requiresShipping, stockQuantity, featured,
207                     sale, smallImage, smallImageURL, smallFile, mediumImage,
208                     mediumImageURL, mediumFile, largeImage, largeImageURL,
209                     largeFile, itemFields, itemPrices, addCommunityPermissions,
210                     addGuestPermissions);
211 
212                 smallFile.delete();
213                 mediumFile.delete();
214                 largeFile.delete();
215             }
216         }
217         catch (IOException ioe) {
218             throw new SystemException(ioe);
219         }
220     }
221 
222     public ShoppingItem addItem(
223             long userId, long categoryId, String sku, String name,
224             String description, String properties, String fieldsQuantities,
225             boolean requiresShipping, int stockQuantity, boolean featured,
226             Boolean sale, boolean smallImage, String smallImageURL,
227             File smallFile, boolean mediumImage, String mediumImageURL,
228             File mediumFile, boolean largeImage, String largeImageURL,
229             File largeFile, List itemFields, List itemPrices,
230             boolean addCommunityPermissions, boolean addGuestPermissions)
231         throws PortalException, SystemException {
232 
233         return addItem(
234             userId, categoryId, sku, name, description, properties,
235             fieldsQuantities, requiresShipping, stockQuantity, featured, sale,
236             smallImage, smallImageURL, smallFile, mediumImage, mediumImageURL,
237             mediumFile, largeImage, largeImageURL, largeFile, itemFields,
238             itemPrices, Boolean.valueOf(addCommunityPermissions),
239             Boolean.valueOf(addGuestPermissions), null, null);
240     }
241 
242     public ShoppingItem addItem(
243             long userId, long categoryId, String sku, String name,
244             String description, String properties, String fieldsQuantities,
245             boolean requiresShipping, int stockQuantity, boolean featured,
246             Boolean sale, boolean smallImage, String smallImageURL,
247             File smallFile, boolean mediumImage, String mediumImageURL,
248             File mediumFile, boolean largeImage, String largeImageURL,
249             File largeFile, List itemFields, List itemPrices,
250             String[] communityPermissions, String[] guestPermissions)
251         throws PortalException, SystemException {
252 
253         return addItem(
254             userId, categoryId, sku, name, description, properties,
255             fieldsQuantities, requiresShipping, stockQuantity, featured, sale,
256             smallImage, smallImageURL, smallFile, mediumImage, mediumImageURL,
257             mediumFile, largeImage, largeImageURL, largeFile, itemFields,
258             itemPrices, null, null, communityPermissions, guestPermissions);
259     }
260 
261     public ShoppingItem addItem(
262             long userId, long categoryId, String sku, String name,
263             String description, String properties, String fieldsQuantities,
264             boolean requiresShipping, int stockQuantity, boolean featured,
265             Boolean sale, boolean smallImage, String smallImageURL,
266             File smallFile, boolean mediumImage, String mediumImageURL,
267             File mediumFile, boolean largeImage, String largeImageURL,
268             File largeFile, List itemFields, List itemPrices,
269             Boolean addCommunityPermissions, Boolean addGuestPermissions,
270             String[] communityPermissions, String[] guestPermissions)
271         throws PortalException, SystemException {
272 
273         // Item
274 
275         User user = UserUtil.findByPrimaryKey(userId);
276         ShoppingCategory category =
277             ShoppingCategoryUtil.findByPrimaryKey(categoryId);
278         sku = sku.trim().toUpperCase();
279 
280         byte[] smallBytes = null;
281         byte[] mediumBytes = null;
282         byte[] largeBytes = null;
283 
284         try {
285             smallBytes = FileUtil.getBytes(smallFile);
286             mediumBytes = FileUtil.getBytes(mediumFile);
287             largeBytes = FileUtil.getBytes(largeFile);
288         }
289         catch (IOException ioe) {
290         }
291 
292         Date now = new Date();
293 
294         validate(
295             user.getCompanyId(), 0, sku, name, smallImage, smallImageURL,
296             smallFile, smallBytes, mediumImage, mediumImageURL, mediumFile,
297             mediumBytes, largeImage, largeImageURL, largeFile, largeBytes);
298 
299         long itemId = CounterLocalServiceUtil.increment();
300 
301         ShoppingItem item = ShoppingItemUtil.create(itemId);
302 
303         item.setCompanyId(user.getCompanyId());
304         item.setUserId(user.getUserId());
305         item.setUserName(user.getFullName());
306         item.setCreateDate(now);
307         item.setModifiedDate(now);
308         item.setCategoryId(categoryId);
309         item.setSku(sku);
310         item.setName(name);
311         item.setDescription(description);
312         item.setProperties(properties);
313         item.setFields(itemFields.size() > 0);
314         item.setFieldsQuantities(fieldsQuantities);
315 
316         for (int i = 0; i < itemPrices.size(); i++) {
317             ShoppingItemPrice itemPrice = (ShoppingItemPrice)itemPrices.get(i);
318 
319             if (itemPrice.getStatus() ==
320                     ShoppingItemPriceImpl.STATUS_ACTIVE_DEFAULT) {
321 
322                 item.setMinQuantity(itemPrice.getMinQuantity());
323                 item.setMaxQuantity(itemPrice.getMaxQuantity());
324                 item.setPrice(itemPrice.getPrice());
325                 item.setDiscount(itemPrice.getDiscount());
326                 item.setTaxable(itemPrice.getTaxable());
327                 item.setShipping(itemPrice.getShipping());
328                 item.setUseShippingFormula(
329                     itemPrice.getUseShippingFormula());
330             }
331 
332             if ((sale == null) && (itemPrice.getDiscount() > 0) &&
333                 ((itemPrice.getStatus() ==
334                     ShoppingItemPriceImpl.STATUS_ACTIVE_DEFAULT) ||
335                 (itemPrice.getStatus() ==
336                     ShoppingItemPriceImpl.STATUS_ACTIVE))) {
337 
338                 sale = Boolean.TRUE;
339             }
340         }
341 
342         item.setRequiresShipping(requiresShipping);
343         item.setStockQuantity(stockQuantity);
344         item.setFeatured(featured);
345         item.setSale((sale != null) ? sale.booleanValue() : false);
346         item.setSmallImage(smallImage);
347         item.setSmallImageId(CounterLocalServiceUtil.increment());
348         item.setSmallImageURL(smallImageURL);
349         item.setMediumImage(mediumImage);
350         item.setMediumImageId(CounterLocalServiceUtil.increment());
351         item.setMediumImageURL(mediumImageURL);
352         item.setLargeImage(largeImage);
353         item.setLargeImageId(CounterLocalServiceUtil.increment());
354         item.setLargeImageURL(largeImageURL);
355 
356         ShoppingItemUtil.update(item);
357 
358         // Fields
359 
360         for (int i = 0; i < itemFields.size(); i++) {
361             ShoppingItemField itemField = (ShoppingItemField)itemFields.get(i);
362 
363             long itemFieldId = CounterLocalServiceUtil.increment();
364 
365             itemField.setItemFieldId(itemFieldId);
366             itemField.setItemId(itemId);
367             itemField.setName(checkItemField(itemField.getName()));
368             itemField.setValues(checkItemField(itemField.getValues()));
369 
370             ShoppingItemFieldUtil.update(itemField);
371         }
372 
373         // Prices
374 
375         for (int i = 0; (i < itemPrices.size()) && (itemPrices.size() > 1);
376                 i++) {
377 
378             ShoppingItemPrice itemPrice = (ShoppingItemPrice)itemPrices.get(i);
379 
380             long itemPriceId = CounterLocalServiceUtil.increment();
381 
382             itemPrice.setItemPriceId(itemPriceId);
383             itemPrice.setItemId(itemId);
384 
385             ShoppingItemPriceUtil.update(itemPrice);
386         }
387 
388         // Images
389 
390         saveImages(
391             smallImage, item.getSmallImageId(), smallFile, smallBytes,
392             mediumImage, item.getMediumImageId(), mediumFile, mediumBytes,
393             largeImage, item.getLargeImageId(), largeFile, largeBytes);
394 
395         // Resources
396 
397         if ((addCommunityPermissions != null) &&
398             (addGuestPermissions != null)) {
399 
400             addItemResources(
401                 category, item, addCommunityPermissions.booleanValue(),
402                 addGuestPermissions.booleanValue());
403         }
404         else {
405             addItemResources(
406                 category, item, communityPermissions, guestPermissions);
407         }
408 
409         return item;
410     }
411 
412     public void addItemResources(
413             long itemId, boolean addCommunityPermissions,
414             boolean addGuestPermissions)
415         throws PortalException, SystemException {
416 
417         ShoppingItem item = ShoppingItemUtil.findByPrimaryKey(itemId);
418         ShoppingCategory category = item.getCategory();
419 
420         addItemResources(
421             category, item, addCommunityPermissions, addGuestPermissions);
422     }
423 
424     public void addItemResources(
425             ShoppingCategory category, ShoppingItem item,
426             boolean addCommunityPermissions, boolean addGuestPermissions)
427         throws PortalException, SystemException {
428 
429         ResourceLocalServiceUtil.addResources(
430             item.getCompanyId(), category.getGroupId(), item.getUserId(),
431             ShoppingItem.class.getName(), item.getItemId(), false,
432             addCommunityPermissions, addGuestPermissions);
433     }
434 
435     public void addItemResources(
436             long itemId, String[] communityPermissions,
437             String[] guestPermissions)
438         throws PortalException, SystemException {
439 
440         ShoppingItem item = ShoppingItemUtil.findByPrimaryKey(itemId);
441         ShoppingCategory category = item.getCategory();
442 
443         addItemResources(
444             category, item, communityPermissions, guestPermissions);
445     }
446 
447     public void addItemResources(
448             ShoppingCategory category, ShoppingItem item,
449             String[] communityPermissions, String[] guestPermissions)
450         throws PortalException, SystemException {
451 
452         ResourceLocalServiceUtil.addModelResources(
453             item.getCompanyId(), category.getGroupId(), item.getUserId(),
454             ShoppingItem.class.getName(), item.getItemId(),
455             communityPermissions, guestPermissions);
456     }
457 
458     public void deleteItem(long itemId)
459         throws PortalException, SystemException {
460 
461         ShoppingItem item = ShoppingItemUtil.findByPrimaryKey(itemId);
462 
463         deleteItem(item);
464     }
465 
466     public void deleteItem(ShoppingItem item)
467         throws PortalException, SystemException {
468 
469         // Fields
470 
471         ShoppingItemFieldUtil.removeByItemId(item.getItemId());
472 
473         // Prices
474 
475         ShoppingItemPriceUtil.removeByItemId(item.getItemId());
476 
477         // Images
478 
479         ImageLocalUtil.deleteImage(item.getSmallImageId());
480         ImageLocalUtil.deleteImage(item.getMediumImageId());
481         ImageLocalUtil.deleteImage(item.getLargeImageId());
482 
483         // Resources
484 
485         ResourceLocalServiceUtil.deleteResource(
486             item.getCompanyId(), ShoppingItem.class.getName(),
487             ResourceImpl.SCOPE_INDIVIDUAL, item.getItemId());
488 
489         // Item
490 
491         ShoppingItemUtil.remove(item.getItemId());
492     }
493 
494     public void deleteItems(long categoryId)
495         throws PortalException, SystemException {
496 
497         Iterator itr = ShoppingItemUtil.findByCategoryId(categoryId).iterator();
498 
499         while (itr.hasNext()) {
500             ShoppingItem item = (ShoppingItem)itr.next();
501 
502             deleteItem(item);
503         }
504     }
505 
506     public int getCategoriesItemsCount(List categoryIds)
507         throws SystemException {
508 
509         return ShoppingItemFinder.countByCategoryIds(categoryIds);
510     }
511 
512     public List getFeaturedItems(
513             long groupId, long categoryId, int numOfItems)
514         throws SystemException {
515 
516         List featuredItems = ShoppingItemFinder.findByFeatured(
517             groupId, new long[] {categoryId}, numOfItems);
518 
519         if (featuredItems.size() == 0) {
520             List childCategories =
521                 ShoppingCategoryUtil.findByG_P(groupId, categoryId);
522 
523             if (childCategories.size() > 0) {
524                 long[] categoryIds = new long[childCategories.size()];
525 
526                 for (int i = 0; i < childCategories.size(); i++) {
527                     ShoppingCategory childCategory =
528                         (ShoppingCategory)childCategories.get(i);
529 
530                     categoryIds[i] = childCategory.getCategoryId();
531                 }
532 
533                 featuredItems = ShoppingItemFinder.findByFeatured(
534                     groupId, categoryIds, numOfItems);
535             }
536         }
537 
538         return featuredItems;
539     }
540 
541     public ShoppingItem getItem(long itemId)
542         throws PortalException, SystemException {
543 
544         return ShoppingItemUtil.findByPrimaryKey(itemId);
545     }
546 
547     public ShoppingItem getItem(long companyId, String sku)
548         throws PortalException, SystemException {
549 
550         return ShoppingItemUtil.findByC_S(companyId, sku);
551     }
552 
553     public List getItems(long categoryId) throws SystemException {
554         return ShoppingItemUtil.findByCategoryId(categoryId);
555     }
556 
557     public List getItems(
558             long categoryId, int begin, int end, OrderByComparator obc)
559         throws SystemException {
560 
561         return ShoppingItemUtil.findByCategoryId(categoryId, begin, end, obc);
562     }
563 
564     public ShoppingItem[] getItemsPrevAndNext(
565             long itemId, OrderByComparator obc)
566         throws PortalException, SystemException {
567 
568         ShoppingItem item = ShoppingItemUtil.findByPrimaryKey(itemId);
569 
570         return ShoppingItemUtil.findByCategoryId_PrevAndNext(
571             item.getItemId(), item.getCategoryId(), obc);
572     }
573 
574     public int getItemsCount(long categoryId) throws SystemException {
575         return ShoppingItemUtil.countByCategoryId(categoryId);
576     }
577 
578     public List getSaleItems(long groupId, long categoryId, int numOfItems)
579         throws SystemException {
580 
581         List saleItems = ShoppingItemFinder.findBySale(
582             groupId, new long[] {categoryId}, numOfItems);
583 
584         if (saleItems.size() == 0) {
585             List childCategories =
586                 ShoppingCategoryUtil.findByG_P(groupId, categoryId);
587 
588             if (childCategories.size() > 0) {
589                 long[] categoryIds = new long[childCategories.size()];
590 
591                 for (int i = 0; i < childCategories.size(); i++) {
592                     ShoppingCategory childCategory =
593                         (ShoppingCategory)childCategories.get(i);
594 
595                     categoryIds[i] = childCategory.getCategoryId();
596                 }
597 
598                 saleItems = ShoppingItemFinder.findBySale(
599                     groupId, categoryIds, numOfItems);
600             }
601         }
602 
603         return saleItems;
604     }
605 
606     public List search(
607             long groupId, long[] categoryIds, String keywords, int begin,
608             int end)
609         throws SystemException {
610 
611         return ShoppingItemFinder.findByKeywords(
612             groupId, categoryIds, keywords, begin, end);
613     }
614 
615     public int searchCount(long groupId, long[] categoryIds, String keywords)
616         throws SystemException {
617 
618         return ShoppingItemFinder.countByKeywords(
619             groupId, categoryIds, keywords);
620     }
621 
622     public ShoppingItem updateItem(
623             long userId, long itemId, long categoryId, String sku, String name,
624             String description, String properties, String fieldsQuantities,
625             boolean requiresShipping, int stockQuantity, boolean featured,
626             Boolean sale, boolean smallImage, String smallImageURL,
627             File smallFile, boolean mediumImage, String mediumImageURL,
628             File mediumFile, boolean largeImage, String largeImageURL,
629             File largeFile, List itemFields, List itemPrices)
630         throws PortalException, SystemException {
631 
632         // Item
633 
634         ShoppingItem item = ShoppingItemUtil.findByPrimaryKey(itemId);
635 
636         User user = UserUtil.findByPrimaryKey(userId);
637         ShoppingCategory category = getCategory(item, categoryId);
638         sku = sku.trim().toUpperCase();
639 
640         byte[] smallBytes = null;
641         byte[] mediumBytes = null;
642         byte[] largeBytes = null;
643 
644         try {
645             smallBytes = FileUtil.getBytes(smallFile);
646             mediumBytes = FileUtil.getBytes(mediumFile);
647             largeBytes = FileUtil.getBytes(largeFile);
648         }
649         catch (IOException ioe) {
650         }
651 
652         validate(
653             user.getCompanyId(), itemId, sku, name, smallImage, smallImageURL,
654             smallFile, smallBytes, mediumImage, mediumImageURL, mediumFile,
655             mediumBytes, largeImage, largeImageURL, largeFile, largeBytes);
656 
657         item.setModifiedDate(new Date());
658         item.setCategoryId(category.getCategoryId());
659         item.setSku(sku);
660         item.setName(name);
661         item.setDescription(description);
662         item.setProperties(properties);
663         item.setFields(itemFields.size() > 0);
664         item.setFieldsQuantities(fieldsQuantities);
665 
666         for (int i = 0; i < itemPrices.size(); i++) {
667             ShoppingItemPrice itemPrice = (ShoppingItemPrice)itemPrices.get(i);
668 
669             if (itemPrice.getStatus() ==
670                     ShoppingItemPriceImpl.STATUS_ACTIVE_DEFAULT) {
671 
672                 item.setMinQuantity(itemPrice.getMinQuantity());
673                 item.setMaxQuantity(itemPrice.getMaxQuantity());
674                 item.setPrice(itemPrice.getPrice());
675                 item.setDiscount(itemPrice.getDiscount());
676                 item.setTaxable(itemPrice.getTaxable());
677                 item.setShipping(itemPrice.getShipping());
678                 item.setUseShippingFormula(
679                     itemPrice.getUseShippingFormula());
680             }
681 
682             if ((sale == null) && (itemPrice.getDiscount() > 0) &&
683                 ((itemPrice.getStatus() ==
684                     ShoppingItemPriceImpl.STATUS_ACTIVE_DEFAULT) ||
685                 (itemPrice.getStatus() ==
686                     ShoppingItemPriceImpl.STATUS_ACTIVE))) {
687 
688                 sale = Boolean.TRUE;
689             }
690         }
691 
692         item.setRequiresShipping(requiresShipping);
693         item.setStockQuantity(stockQuantity);
694         item.setFeatured(featured);
695         item.setSale((sale != null) ? sale.booleanValue() : false);
696         item.setSmallImage(smallImage);
697         item.setSmallImageURL(smallImageURL);
698         item.setMediumImage(mediumImage);
699         item.setMediumImageURL(mediumImageURL);
700         item.setLargeImage(largeImage);
701         item.setLargeImageURL(largeImageURL);
702 
703         ShoppingItemUtil.update(item);
704 
705         // Fields
706 
707         ShoppingItemFieldUtil.removeByItemId(itemId);
708 
709         for (int i = 0; i < itemFields.size() && itemFields.size() > 0; i++) {
710             ShoppingItemField itemField = (ShoppingItemField)itemFields.get(i);
711 
712             long itemFieldId = CounterLocalServiceUtil.increment();
713 
714             itemField.setItemFieldId(itemFieldId);
715             itemField.setItemId(itemId);
716             itemField.setName(checkItemField(itemField.getName()));
717             itemField.setValues(checkItemField(itemField.getValues()));
718 
719             ShoppingItemFieldUtil.update(itemField);
720         }
721 
722         // Prices
723 
724         ShoppingItemPriceUtil.removeByItemId(itemId);
725 
726         for (int i = 0; i < itemPrices.size() && itemPrices.size() > 1; i++) {
727             ShoppingItemPrice itemPrice = (ShoppingItemPrice)itemPrices.get(i);
728 
729             long itemPriceId = CounterLocalServiceUtil.increment();
730 
731             itemPrice.setItemPriceId(itemPriceId);
732             itemPrice.setItemId(itemId);
733 
734             ShoppingItemPriceUtil.update(itemPrice);
735         }
736 
737         // Images
738 
739         saveImages(
740             smallImage, item.getSmallImageId(), smallFile, smallBytes,
741             mediumImage, item.getMediumImageId(), mediumFile, mediumBytes,
742             largeImage, item.getLargeImageId(), largeFile, largeBytes);
743 
744         return item;
745     }
746 
747     protected String checkItemField(String value) {
748         return StringUtil.replace(
749             value,
750             new String[] {
751                 "\"", "&", "'", ".", "=", "|"
752             },
753             new String[] {
754                 StringPool.BLANK,
755                 StringPool.BLANK,
756                 StringPool.BLANK,
757                 StringPool.BLANK,
758                 StringPool.BLANK,
759                 StringPool.BLANK
760             }
761         );
762     }
763 
764     protected String getBookProperties(AmazonRankings amazonRankings) {
765         String isbn = amazonRankings.getISBN();
766 
767         String authors = StringUtil.merge(amazonRankings.getAuthors(), ", ");
768 
769         String publisher =
770             amazonRankings.getManufacturer() + "; (" +
771             amazonRankings.getReleaseDateAsString() + ")";
772 
773         String properties =
774             "ISBN=" + isbn + "\nAuthor=" + authors + "\nPublisher=" + publisher;
775 
776         return properties;
777     }
778 
779     protected ShoppingCategory getCategory(ShoppingItem item, long categoryId)
780         throws PortalException, SystemException {
781 
782         if (item.getCategoryId() != categoryId) {
783             ShoppingCategory oldCategory =
784                 ShoppingCategoryUtil.findByPrimaryKey(item.getCategoryId());
785 
786             ShoppingCategory newCategory =
787                 ShoppingCategoryUtil.fetchByPrimaryKey(categoryId);
788 
789             if ((newCategory == null) ||
790                 (oldCategory.getGroupId() != newCategory.getGroupId())) {
791 
792                 categoryId = item.getCategoryId();
793             }
794         }
795 
796         return ShoppingCategoryUtil.findByPrimaryKey(categoryId);
797     }
798 
799     protected void saveImages(
800             boolean smallImage, long smallImageId, File smallFile,
801             byte[] smallBytes, boolean mediumImage, long mediumImageId,
802             File mediumFile, byte[] mediumBytes, boolean largeImage,
803             long largeImageId, File largeFile, byte[] largeBytes)
804         throws SystemException {
805 
806         // Small image
807 
808         if (smallImage) {
809             if ((smallFile != null) && (smallBytes != null)) {
810                 ImageLocalUtil.updateImage(smallImageId, smallBytes);
811             }
812         }
813         else {
814             ImageLocalUtil.deleteImage(smallImageId);
815         }
816 
817         // Medium image
818 
819         if (mediumImage) {
820             if ((mediumFile != null) && (mediumBytes != null)) {
821                 ImageLocalUtil.updateImage(mediumImageId, mediumBytes);
822             }
823         }
824         else {
825             ImageLocalUtil.deleteImage(mediumImageId);
826         }
827 
828         // Large image
829 
830         if (largeImage) {
831             if ((largeFile != null) && (largeBytes != null)) {
832                 ImageLocalUtil.updateImage(largeImageId, largeBytes);
833             }
834         }
835         else {
836             ImageLocalUtil.deleteImage(largeImageId);
837         }
838     }
839 
840     protected void validate(
841             long companyId, long itemId, String sku, String name,
842             boolean smallImage, String smallImageURL, File smallFile,
843             byte[] smallBytes, boolean mediumImage, String mediumImageURL,
844             File mediumFile, byte[] mediumBytes, boolean largeImage,
845             String largeImageURL, File largeFile, byte[] largeBytes)
846         throws PortalException, SystemException {
847 
848         if (Validator.isNull(sku)) {
849             throw new ItemSKUException();
850         }
851 
852         try {
853             ShoppingItem item = ShoppingItemUtil.findByC_S(companyId, sku);
854 
855             if (itemId > 0) {
856                 if (item.getItemId() != itemId) {
857                     throw new DuplicateItemSKUException();
858                 }
859             }
860             else {
861                 throw new DuplicateItemSKUException();
862             }
863         }
864         catch (NoSuchItemException nsie) {
865         }
866 
867         if (Validator.isNull(name)) {
868             throw new ItemNameException();
869         }
870 
871         String[] imageExtensions =
872             PropsUtil.getArray(PropsUtil.SHOPPING_IMAGE_EXTENSIONS);
873 
874         // Small image
875 
876         if (smallImage && Validator.isNull(smallImageURL) &&
877             smallFile != null && smallBytes != null) {
878 
879             String smallImageName = smallFile.getName();
880 
881             if (smallImageName != null) {
882                 boolean validSmallImageExtension = false;
883 
884                 for (int i = 0; i < imageExtensions.length; i++) {
885                     if (StringPool.STAR.equals(imageExtensions[i]) ||
886                         StringUtil.endsWith(
887                             smallImageName, imageExtensions[i])) {
888 
889                         validSmallImageExtension = true;
890 
891                         break;
892                     }
893                 }
894 
895                 if (!validSmallImageExtension) {
896                     throw new ItemSmallImageNameException(smallImageName);
897                 }
898             }
899 
900             long smallImageMaxSize = GetterUtil.getLong(
901                 PropsUtil.get(PropsUtil.SHOPPING_IMAGE_SMALL_MAX_SIZE));
902 
903             if ((smallImageMaxSize > 0) &&
904                 ((smallBytes == null) ||
905                     (smallBytes.length > smallImageMaxSize))) {
906 
907                 throw new ItemSmallImageSizeException();
908             }
909         }
910 
911         // Medium image
912 
913         if (mediumImage && Validator.isNull(mediumImageURL) &&
914             mediumFile != null && mediumBytes != null) {
915 
916             String mediumImageName = mediumFile.getName();
917 
918             if (mediumImageName != null) {
919                 boolean validMediumImageExtension = false;
920 
921                 for (int i = 0; i < imageExtensions.length; i++) {
922                     if (StringPool.STAR.equals(imageExtensions[i]) ||
923                         StringUtil.endsWith(
924                             mediumImageName, imageExtensions[i])) {
925 
926                         validMediumImageExtension = true;
927 
928                         break;
929                     }
930                 }
931 
932                 if (!validMediumImageExtension) {
933                     throw new ItemMediumImageNameException(mediumImageName);
934                 }
935             }
936 
937             long mediumImageMaxSize = GetterUtil.getLong(
938                 PropsUtil.get(PropsUtil.SHOPPING_IMAGE_MEDIUM_MAX_SIZE));
939 
940             if ((mediumImageMaxSize > 0) &&
941                 ((mediumBytes == null) ||
942                     (mediumBytes.length > mediumImageMaxSize))) {
943 
944                 throw new ItemMediumImageSizeException();
945             }
946         }
947 
948         // Large image
949 
950         if (largeImage && Validator.isNull(largeImageURL) &&
951             largeFile != null && largeBytes != null) {
952 
953             String largeImageName = largeFile.getName();
954 
955             if (largeImageName != null) {
956                 boolean validLargeImageExtension = false;
957 
958                 for (int i = 0; i < imageExtensions.length; i++) {
959                     if (StringPool.STAR.equals(imageExtensions[i]) ||
960                         StringUtil.endsWith(
961                             largeImageName, imageExtensions[i])) {
962 
963                         validLargeImageExtension = true;
964 
965                         break;
966                     }
967                 }
968 
969                 if (!validLargeImageExtension) {
970                     throw new ItemLargeImageNameException(largeImageName);
971                 }
972             }
973 
974             long largeImageMaxSize = GetterUtil.getLong(
975                 PropsUtil.get(PropsUtil.SHOPPING_IMAGE_LARGE_MAX_SIZE));
976 
977             if ((largeImageMaxSize > 0) &&
978                 ((largeBytes == null) ||
979                     (largeBytes.length > largeImageMaxSize))) {
980 
981                 throw new ItemLargeImageSizeException();
982             }
983         }
984     }
985 
986 }