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