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