001    /**
002     * Copyright (c) 2000-2012 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.SystemProperties;
026    import com.liferay.portal.kernel.util.Validator;
027    import com.liferay.portal.model.ResourceConstants;
028    import com.liferay.portal.model.User;
029    import com.liferay.portal.service.ServiceContext;
030    import com.liferay.portal.util.PrefsPropsUtil;
031    import com.liferay.portlet.amazonrankings.model.AmazonRankings;
032    import com.liferay.portlet.amazonrankings.util.AmazonRankingsUtil;
033    import com.liferay.portlet.shopping.AmazonException;
034    import com.liferay.portlet.shopping.DuplicateItemSKUException;
035    import com.liferay.portlet.shopping.ItemLargeImageNameException;
036    import com.liferay.portlet.shopping.ItemLargeImageSizeException;
037    import com.liferay.portlet.shopping.ItemMediumImageNameException;
038    import com.liferay.portlet.shopping.ItemMediumImageSizeException;
039    import com.liferay.portlet.shopping.ItemNameException;
040    import com.liferay.portlet.shopping.ItemSKUException;
041    import com.liferay.portlet.shopping.ItemSmallImageNameException;
042    import com.liferay.portlet.shopping.ItemSmallImageSizeException;
043    import com.liferay.portlet.shopping.model.ShoppingCategory;
044    import com.liferay.portlet.shopping.model.ShoppingCategoryConstants;
045    import com.liferay.portlet.shopping.model.ShoppingItem;
046    import com.liferay.portlet.shopping.model.ShoppingItemField;
047    import com.liferay.portlet.shopping.model.ShoppingItemPrice;
048    import com.liferay.portlet.shopping.model.ShoppingItemPriceConstants;
049    import com.liferay.portlet.shopping.service.base.ShoppingItemLocalServiceBaseImpl;
050    import com.liferay.util.PwdGenerator;
051    
052    import java.io.File;
053    import java.io.FileOutputStream;
054    import java.io.IOException;
055    import java.io.OutputStream;
056    
057    import java.util.ArrayList;
058    import java.util.Date;
059    import java.util.List;
060    
061    /**
062     * @author Brian Wing Shun Chan
063     */
064    public class ShoppingItemLocalServiceImpl
065            extends ShoppingItemLocalServiceBaseImpl {
066    
067            public void addBookItems(
068                            long userId, long groupId, long categoryId, String[] isbns)
069                    throws PortalException, SystemException {
070    
071                    try {
072                            doAddBookItems(userId, groupId, categoryId, isbns);
073                    }
074                    catch (IOException ioe) {
075                            throw new SystemException(ioe);
076                    }
077            }
078    
079            public ShoppingItem addItem(
080                            long userId, long groupId, long categoryId, String sku, String name,
081                            String description, String properties, String fieldsQuantities,
082                            boolean requiresShipping, int stockQuantity, boolean featured,
083                            Boolean sale, boolean smallImage, String smallImageURL,
084                            File smallImageFile, boolean mediumImage, String mediumImageURL,
085                            File mediumImageFile, boolean largeImage, String largeImageURL,
086                            File largeImageFile, List<ShoppingItemField> itemFields,
087                            List<ShoppingItemPrice> itemPrices, ServiceContext serviceContext)
088                    throws PortalException, SystemException {
089    
090                    // Item
091    
092                    User user = userPersistence.findByPrimaryKey(userId);
093                    sku = sku.trim().toUpperCase();
094    
095                    byte[] smallImageBytes = null;
096                    byte[] mediumImageBytes = null;
097                    byte[] largeImageBytes = null;
098    
099                    try {
100                            smallImageBytes = FileUtil.getBytes(smallImageFile);
101                            mediumImageBytes = FileUtil.getBytes(mediumImageFile);
102                            largeImageBytes = FileUtil.getBytes(largeImageFile);
103                    }
104                    catch (IOException ioe) {
105                    }
106    
107                    Date now = new Date();
108    
109                    validate(
110                            user.getCompanyId(), 0, sku, name, smallImage, smallImageURL,
111                            smallImageFile, smallImageBytes, mediumImage, mediumImageURL,
112                            mediumImageFile, mediumImageBytes, largeImage, largeImageURL,
113                            largeImageFile, largeImageBytes);
114    
115                    long itemId = counterLocalService.increment();
116    
117                    ShoppingItem item = shoppingItemPersistence.create(itemId);
118    
119                    item.setGroupId(groupId);
120                    item.setCompanyId(user.getCompanyId());
121                    item.setUserId(user.getUserId());
122                    item.setUserName(user.getFullName());
123                    item.setCreateDate(now);
124                    item.setModifiedDate(now);
125                    item.setCategoryId(categoryId);
126                    item.setSku(sku);
127                    item.setName(name);
128                    item.setDescription(description);
129                    item.setProperties(properties);
130                    item.setFields(itemFields.size() > 0);
131                    item.setFieldsQuantities(fieldsQuantities);
132    
133                    for (ShoppingItemPrice itemPrice : itemPrices) {
134                            if (itemPrice.getStatus() ==
135                                            ShoppingItemPriceConstants.STATUS_ACTIVE_DEFAULT) {
136    
137                                    item.setMinQuantity(itemPrice.getMinQuantity());
138                                    item.setMaxQuantity(itemPrice.getMaxQuantity());
139                                    item.setPrice(itemPrice.getPrice());
140                                    item.setDiscount(itemPrice.getDiscount());
141                                    item.setTaxable(itemPrice.getTaxable());
142                                    item.setShipping(itemPrice.getShipping());
143                                    item.setUseShippingFormula(itemPrice.getUseShippingFormula());
144                            }
145    
146                            if ((sale == null) && (itemPrice.getDiscount() > 0) &&
147                                    ((itemPrice.getStatus() ==
148                                             ShoppingItemPriceConstants.STATUS_ACTIVE_DEFAULT) ||
149                                     (itemPrice.getStatus() ==
150                                             ShoppingItemPriceConstants.STATUS_ACTIVE))) {
151    
152                                    sale = Boolean.TRUE;
153                            }
154                    }
155    
156                    item.setRequiresShipping(requiresShipping);
157                    item.setStockQuantity(stockQuantity);
158                    item.setFeatured(featured);
159                    item.setSale((sale != null) ? sale.booleanValue() : false);
160                    item.setSmallImage(smallImage);
161                    item.setSmallImageId(counterLocalService.increment());
162                    item.setSmallImageURL(smallImageURL);
163                    item.setMediumImage(mediumImage);
164                    item.setMediumImageId(counterLocalService.increment());
165                    item.setMediumImageURL(mediumImageURL);
166                    item.setLargeImage(largeImage);
167                    item.setLargeImageId(counterLocalService.increment());
168                    item.setLargeImageURL(largeImageURL);
169    
170                    shoppingItemPersistence.update(item, false);
171    
172                    // Resources
173    
174                    if (serviceContext.isAddGroupPermissions() ||
175                            serviceContext.isAddGuestPermissions()) {
176    
177                            addItemResources(
178                                    item, serviceContext.isAddGroupPermissions(),
179                                    serviceContext.isAddGuestPermissions());
180                    }
181                    else {
182                            addItemResources(
183                                    item, serviceContext.getGroupPermissions(),
184                                    serviceContext.getGuestPermissions());
185                    }
186    
187                    // Images
188    
189                    saveImages(
190                            smallImage, item.getSmallImageId(), smallImageFile, smallImageBytes,
191                            mediumImage, item.getMediumImageId(), mediumImageFile,
192                            mediumImageBytes, largeImage, item.getLargeImageId(),
193                            largeImageFile, largeImageBytes);
194    
195                    // Item fields
196    
197                    for (ShoppingItemField itemField : itemFields) {
198                            long itemFieldId = counterLocalService.increment();
199    
200                            itemField.setItemFieldId(itemFieldId);
201                            itemField.setItemId(itemId);
202                            itemField.setName(checkItemField(itemField.getName()));
203                            itemField.setValues(checkItemField(itemField.getValues()));
204    
205                            shoppingItemFieldPersistence.update(itemField, false);
206                    }
207    
208                    // Item prices
209    
210                    if (itemPrices.size() > 1) {
211                            for (ShoppingItemPrice itemPrice : itemPrices) {
212                                    long itemPriceId = counterLocalService.increment();
213    
214                                    itemPrice.setItemPriceId(itemPriceId);
215                                    itemPrice.setItemId(itemId);
216    
217                                    shoppingItemPricePersistence.update(itemPrice, false);
218                            }
219                    }
220    
221                    return item;
222            }
223    
224            public void addItemResources(
225                            long itemId, boolean addGroupPermissions,
226                            boolean addGuestPermissions)
227                    throws PortalException, SystemException {
228    
229                    ShoppingItem item = shoppingItemPersistence.findByPrimaryKey(itemId);
230    
231                    addItemResources(item, addGroupPermissions, addGuestPermissions);
232            }
233    
234            public void addItemResources(
235                            long itemId, String[] groupPermissions, String[] guestPermissions)
236                    throws PortalException, SystemException {
237    
238                    ShoppingItem item = shoppingItemPersistence.findByPrimaryKey(itemId);
239    
240                    addItemResources(item, groupPermissions, guestPermissions);
241            }
242    
243            public void addItemResources(
244                            ShoppingItem item, boolean addGroupPermissions,
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                            addGroupPermissions, addGuestPermissions);
252            }
253    
254            public void addItemResources(
255                            ShoppingItem item, String[] groupPermissions,
256                            String[] guestPermissions)
257                    throws PortalException, SystemException {
258    
259                    resourceLocalService.addModelResources(
260                            item.getCompanyId(), item.getGroupId(), item.getUserId(),
261                            ShoppingItem.class.getName(), item.getItemId(), groupPermissions,
262                            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 smallImageFile,
457                            boolean mediumImage, String mediumImageURL, File mediumImageFile,
458                            boolean largeImage, String largeImageURL, File largeImageFile,
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[] smallImageBytes = null;
472                    byte[] mediumImageBytes = null;
473                    byte[] largeImageBytes = null;
474    
475                    try {
476                            smallImageBytes = FileUtil.getBytes(smallImageFile);
477                            mediumImageBytes = FileUtil.getBytes(mediumImageFile);
478                            largeImageBytes = FileUtil.getBytes(largeImageFile);
479                    }
480                    catch (IOException ioe) {
481                    }
482    
483                    validate(
484                            user.getCompanyId(), itemId, sku, name, smallImage, smallImageURL,
485                            smallImageFile, smallImageBytes, mediumImage, mediumImageURL,
486                            mediumImageFile, mediumImageBytes, largeImage, largeImageURL,
487                            largeImageFile, largeImageBytes);
488    
489                    item.setModifiedDate(new Date());
490                    item.setCategoryId(categoryId);
491                    item.setSku(sku);
492                    item.setName(name);
493                    item.setDescription(description);
494                    item.setProperties(properties);
495                    item.setFields(itemFields.size() > 0);
496                    item.setFieldsQuantities(fieldsQuantities);
497    
498                    for (ShoppingItemPrice itemPrice : itemPrices) {
499                            if (itemPrice.getStatus() ==
500                                            ShoppingItemPriceConstants.STATUS_ACTIVE_DEFAULT) {
501    
502                                    item.setMinQuantity(itemPrice.getMinQuantity());
503                                    item.setMaxQuantity(itemPrice.getMaxQuantity());
504                                    item.setPrice(itemPrice.getPrice());
505                                    item.setDiscount(itemPrice.getDiscount());
506                                    item.setTaxable(itemPrice.getTaxable());
507                                    item.setShipping(itemPrice.getShipping());
508                                    item.setUseShippingFormula(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(), smallImageFile, smallImageBytes,
538                            mediumImage, item.getMediumImageId(), mediumImageFile,
539                            mediumImageBytes, largeImage, item.getLargeImageId(),
540                            largeImageFile, largeImageBytes);
541    
542                    // Item fields
543    
544                    shoppingItemFieldPersistence.removeByItemId(itemId);
545    
546                    for (ShoppingItemField itemField : itemFields) {
547                            long itemFieldId = counterLocalService.increment();
548    
549                            itemField.setItemFieldId(itemFieldId);
550                            itemField.setItemId(itemId);
551                            itemField.setName(checkItemField(itemField.getName()));
552                            itemField.setValues(checkItemField(itemField.getValues()));
553    
554                            shoppingItemFieldPersistence.update(itemField, false);
555                    }
556    
557                    // Item prices
558    
559                    shoppingItemPricePersistence.removeByItemId(itemId);
560    
561                    if (itemPrices.size() > 1) {
562                            for (ShoppingItemPrice itemPrice : itemPrices) {
563                                    long itemPriceId = counterLocalService.increment();
564    
565                                    itemPrice.setItemPriceId(itemPriceId);
566                                    itemPrice.setItemId(itemId);
567    
568                                    shoppingItemPricePersistence.update(itemPrice, false);
569                            }
570                    }
571    
572                    return item;
573            }
574    
575            protected String checkItemField(String value) {
576                    return StringUtil.replace(
577                            value,
578                            new String[] {
579                                    "\"", "&", "'", ".", "=", "|"
580                            },
581                            new String[] {
582                                    StringPool.BLANK, StringPool.BLANK, StringPool.BLANK,
583                                    StringPool.BLANK, StringPool.BLANK, StringPool.BLANK
584                            }
585                    );
586            }
587    
588            protected void doAddBookItems(
589                            long userId, long groupId, long categoryId, String[] isbns)
590                    throws IOException, PortalException, SystemException {
591    
592                    if (!AmazonRankingsUtil.isEnabled()) {
593                            throw new AmazonException("Amazon integration is not enabled");
594                    }
595    
596                    String tmpDir = SystemProperties.get(SystemProperties.TMP_DIR);
597    
598                    for (int i = 0; (i < isbns.length) && (i < 50); i++) {
599                            String isbn = isbns[i];
600    
601                            AmazonRankings amazonRankings =
602                                    AmazonRankingsUtil.getAmazonRankings(isbn);
603    
604                            if (amazonRankings == null) {
605                                    continue;
606                            }
607    
608                            String name = amazonRankings.getProductName();
609                            String description = StringPool.BLANK;
610                            String properties = getBookProperties(amazonRankings);
611    
612                            int minQuantity = 0;
613                            int maxQuantity = 0;
614                            double price = amazonRankings.getListPrice();
615                            double discount = 1 - amazonRankings.getOurPrice() / price;
616                            boolean taxable = true;
617                            double shipping = 0.0;
618                            boolean useShippingFormula = true;
619    
620                            ShoppingItemPrice itemPrice = shoppingItemPricePersistence.create(
621                                    0);
622    
623                            itemPrice.setMinQuantity(minQuantity);
624                            itemPrice.setMaxQuantity(maxQuantity);
625                            itemPrice.setPrice(price);
626                            itemPrice.setDiscount(discount);
627                            itemPrice.setTaxable(taxable);
628                            itemPrice.setShipping(shipping);
629                            itemPrice.setUseShippingFormula(useShippingFormula);
630                            itemPrice.setStatus(
631                                    ShoppingItemPriceConstants.STATUS_ACTIVE_DEFAULT);
632    
633                            boolean requiresShipping = true;
634                            int stockQuantity = 0;
635                            boolean featured = false;
636                            Boolean sale = null;
637    
638                            // Small image
639    
640                            boolean smallImage = true;
641                            String smallImageURL = StringPool.BLANK;
642                            File smallImageFile = new File(
643                                    tmpDir + File.separatorChar +
644                                    PwdGenerator.getPassword(
645                                            PwdGenerator.KEY1 + PwdGenerator.KEY2, 12) + ".jpg");
646    
647                            byte[] smallImageBytes = HttpUtil.URLtoByteArray(
648                                    amazonRankings.getSmallImageURL());
649    
650                            if (smallImageBytes.length < 1024) {
651                                    smallImage = false;
652                            }
653                            else {
654                                    OutputStream os = new FileOutputStream(smallImageFile);
655    
656                                    os.write(smallImageBytes);
657    
658                                    os.close();
659                            }
660    
661                            // Medium image
662    
663                            boolean mediumImage = true;
664                            String mediumImageURL = StringPool.BLANK;
665                            File mediumImageFile = new File(
666                                    tmpDir + File.separatorChar +
667                                    PwdGenerator.getPassword(
668                                            PwdGenerator.KEY1 + PwdGenerator.KEY2, 12) + ".jpg");
669    
670                            byte[] mediumImageBytes = HttpUtil.URLtoByteArray(
671                                    amazonRankings.getMediumImageURL());
672    
673                            if (mediumImageBytes.length < 1024) {
674                                    mediumImage = false;
675                            }
676                            else {
677                                    OutputStream os = new FileOutputStream(mediumImageFile);
678    
679                                    os.write(mediumImageBytes);
680    
681                                    os.close();
682                            }
683    
684                            // Large image
685    
686                            boolean largeImage = true;
687                            String largeImageURL = StringPool.BLANK;
688                            File largeImageFile = new File(
689                                    tmpDir + File.separatorChar +
690                                    PwdGenerator.getPassword(
691                                            PwdGenerator.KEY1 + PwdGenerator.KEY2, 12) + ".jpg");
692    
693                            byte[] largeImageBytes = HttpUtil.URLtoByteArray(
694                                    amazonRankings.getLargeImageURL());
695    
696                            if (largeImageBytes.length < 1024) {
697                                    largeImage = false;
698                            }
699                            else {
700                                    OutputStream os = new FileOutputStream(largeImageFile);
701    
702                                    os.write(largeImageBytes);
703    
704                                    os.close();
705                            }
706    
707                            List<ShoppingItemField> itemFields =
708                                    new ArrayList<ShoppingItemField>();
709    
710                            List<ShoppingItemPrice> itemPrices =
711                                    new ArrayList<ShoppingItemPrice>();
712    
713                            itemPrices.add(itemPrice);
714    
715                            ServiceContext serviceContext = new ServiceContext();
716    
717                            serviceContext.setAddGroupPermissions(true);
718                            serviceContext.setAddGuestPermissions(true);
719    
720                            addItem(
721                                    userId, groupId, categoryId, isbn, name, description,
722                                    properties, StringPool.BLANK, requiresShipping, stockQuantity,
723                                    featured, sale, smallImage, smallImageURL, smallImageFile,
724                                    mediumImage, mediumImageURL, mediumImageFile, largeImage,
725                                    largeImageURL, largeImageFile, itemFields, itemPrices,
726                                    serviceContext);
727    
728                            smallImageFile.delete();
729                            mediumImageFile.delete();
730                            largeImageFile.delete();
731                    }
732            }
733    
734            protected String getBookProperties(AmazonRankings amazonRankings) {
735                    String isbn = amazonRankings.getISBN();
736    
737                    String authors = StringUtil.merge(amazonRankings.getAuthors(), ", ");
738    
739                    String publisher =
740                            amazonRankings.getManufacturer() + "; (" +
741                            amazonRankings.getReleaseDateAsString() + ")";
742    
743                    String properties =
744                            "ISBN=" + isbn + "\nAuthor=" + authors + "\nPublisher=" + publisher;
745    
746                    return properties;
747            }
748    
749            protected long getCategory(ShoppingItem item, long categoryId)
750                    throws SystemException {
751    
752                    if ((item.getCategoryId() != categoryId) &&
753                            (categoryId !=
754                                    ShoppingCategoryConstants.DEFAULT_PARENT_CATEGORY_ID)) {
755    
756                            ShoppingCategory newCategory =
757                                    shoppingCategoryPersistence.fetchByPrimaryKey(categoryId);
758    
759                            if ((newCategory == null) ||
760                                    (item.getGroupId() != newCategory.getGroupId())) {
761    
762                                    categoryId = item.getCategoryId();
763                            }
764                    }
765    
766                    return categoryId;
767            }
768    
769            protected void saveImages(
770                            boolean smallImage, long smallImageId, File smallImageFile,
771                            byte[] smallImageBytes, boolean mediumImage, long mediumImageId,
772                            File mediumImageFile, byte[] mediumImageBytes, boolean largeImage,
773                            long largeImageId, File largeImageFile, byte[] largeImageBytes)
774                    throws PortalException, SystemException {
775    
776                    // Small image
777    
778                    if (smallImage) {
779                            if ((smallImageFile != null) && (smallImageBytes != null)) {
780                                    imageLocalService.updateImage(smallImageId, smallImageBytes);
781                            }
782                    }
783                    else {
784                            imageLocalService.deleteImage(smallImageId);
785                    }
786    
787                    // Medium image
788    
789                    if (mediumImage) {
790                            if ((mediumImageFile != null) && (mediumImageBytes != null)) {
791                                    imageLocalService.updateImage(mediumImageId, mediumImageBytes);
792                            }
793                    }
794                    else {
795                            imageLocalService.deleteImage(mediumImageId);
796                    }
797    
798                    // Large image
799    
800                    if (largeImage) {
801                            if ((largeImageFile != null) && (largeImageBytes != null)) {
802                                    imageLocalService.updateImage(largeImageId, largeImageBytes);
803                            }
804                    }
805                    else {
806                            imageLocalService.deleteImage(largeImageId);
807                    }
808            }
809    
810            protected void validate(
811                            long companyId, long itemId, String sku, String name,
812                            boolean smallImage, String smallImageURL, File smallImageFile,
813                            byte[] smallImageBytes, boolean mediumImage, String mediumImageURL,
814                            File mediumImageFile, byte[] mediumImageBytes, boolean largeImage,
815                            String largeImageURL, File largeImageFile, byte[] largeImageBytes)
816                    throws PortalException, SystemException {
817    
818                    if (Validator.isNull(sku)) {
819                            throw new ItemSKUException();
820                    }
821    
822                    ShoppingItem item = shoppingItemPersistence.fetchByC_S(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                            smallImageFile != null && smallImageBytes != null) {
846    
847                            String smallImageName = smallImageFile.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                                    ((smallImageBytes == null) ||
873                                     (smallImageBytes.length > smallImageMaxSize))) {
874    
875                                    throw new ItemSmallImageSizeException();
876                            }
877                    }
878    
879                    // Medium image
880    
881                    if (mediumImage && Validator.isNull(mediumImageURL) &&
882                            mediumImageFile != null && mediumImageBytes != null) {
883    
884                            String mediumImageName = mediumImageFile.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                                    ((mediumImageBytes == null) ||
910                                     (mediumImageBytes.length > mediumImageMaxSize))) {
911    
912                                    throw new ItemMediumImageSizeException();
913                            }
914                    }
915    
916                    // Large image
917    
918                    if (largeImage && Validator.isNull(largeImageURL) &&
919                            largeImageFile != null && largeImageBytes != null) {
920    
921                            String largeImageName = largeImageFile.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                                    ((largeImageBytes == null) ||
947                                     (largeImageBytes.length > largeImageMaxSize))) {
948    
949                                    throw new ItemLargeImageSizeException();
950                            }
951                    }
952            }
953    
954    }