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