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