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