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