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