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