Search in sources :

Example 1 with ExtensionResultStatusType

use of org.broadleafcommerce.common.extension.ExtensionResultStatusType in project BroadleafCommerce by BroadleafCommerce.

the class OrderServiceImpl method findCartForCustomerWithEnhancements.

@Override
public Order findCartForCustomerWithEnhancements(Customer customer, Order candidateOrder) {
    ExtensionResultHolder<Order> erh = new ExtensionResultHolder<Order>();
    ExtensionResultStatusType resultStatusType = extensionManager.findCartForCustomerWithEnhancements(customer, candidateOrder, erh);
    if (ExtensionResultStatusType.NOT_HANDLED != resultStatusType) {
        return erh.getResult();
    }
    return candidateOrder;
}
Also used : Order(org.broadleafcommerce.core.order.domain.Order) ExtensionResultStatusType(org.broadleafcommerce.common.extension.ExtensionResultStatusType) ExtensionResultHolder(org.broadleafcommerce.common.extension.ExtensionResultHolder)

Example 2 with ExtensionResultStatusType

use of org.broadleafcommerce.common.extension.ExtensionResultStatusType in project BroadleafCommerce by BroadleafCommerce.

the class MediaFieldPersistenceProvider method populateValue.

@Override
public MetadataProviderResponse populateValue(PopulateValueRequest populateValueRequest, Serializable instance) throws PersistenceException {
    if (!canHandlePersistence(populateValueRequest, instance)) {
        return MetadataProviderResponse.NOT_HANDLED;
    }
    String prop = populateValueRequest.getProperty().getName();
    if (prop.contains(FieldManager.MAPFIELDSEPARATOR)) {
        Field field = populateValueRequest.getFieldManager().getField(instance.getClass(), prop.substring(0, prop.indexOf(FieldManager.MAPFIELDSEPARATOR)));
        if (field.getAnnotation(OneToMany.class) == null) {
            throw new UnsupportedOperationException("MediaFieldPersistenceProvider is currently only compatible with map fields when modelled using @OneToMany");
        }
    }
    MetadataProviderResponse response = MetadataProviderResponse.HANDLED;
    boolean dirty = false;
    try {
        setNonDisplayableValues(populateValueRequest);
        Class<?> valueType = getStartingValueType(populateValueRequest);
        if (Media.class.isAssignableFrom(valueType)) {
            Media newMedia = mediaBuilderService.convertJsonToMedia(populateValueRequest.getProperty().getUnHtmlEncodedValue(), valueType);
            boolean persist = false;
            boolean noPrimary = false;
            boolean update = false;
            Media media;
            Boolean cleared;
            try {
                checkExtension: {
                    if (extensionManager != null) {
                        ExtensionResultHolder<Tuple<Media, Boolean>> result = new ExtensionResultHolder<Tuple<Media, Boolean>>();
                        ExtensionResultStatusType statusType = extensionManager.getProxy().retrieveMedia(instance, populateValueRequest, result);
                        if (ExtensionResultStatusType.NOT_HANDLED != statusType) {
                            Tuple<Media, Boolean> tuple = result.getResult();
                            media = tuple.getFirst();
                            cleared = tuple.getSecond();
                            break checkExtension;
                        }
                    }
                    media = (Media) populateValueRequest.getFieldManager().getFieldValue(instance, populateValueRequest.getProperty().getName());
                    cleared = false;
                }
                if (newMedia == null) {
                    noPrimary = true;
                    dirty = true;
                    update = false;
                    if (!cleared && media != null) {
                        // remove entry in sku to media map
                        populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), null);
                        populateValueRequest.getPersistenceManager().getDynamicEntityDao().remove(media);
                    }
                } else if (media == null) {
                    media = (Media) valueType.newInstance();
                    mediaBuilderService.instantiateMediaFields(media);
                    Object parent = extractParent(populateValueRequest, instance);
                    populateValueRequest.getFieldManager().setFieldValue(media, populateValueRequest.getMetadata().getToOneParentProperty(), parent);
                    populateValueRequest.getFieldManager().setFieldValue(media, populateValueRequest.getMetadata().getMapKeyValueProperty(), prop.substring(prop.indexOf(FieldManager.MAPFIELDSEPARATOR) + FieldManager.MAPFIELDSEPARATOR.length(), prop.length()));
                    persist = true;
                }
            } catch (FieldNotAvailableException e) {
                throw new IllegalArgumentException(e);
            }
            if (media != null) {
                if (media instanceof Status && 'Y' == ((Status) media).getArchived()) {
                    persist = true;
                }
                populateValueRequest.getProperty().setOriginalValue(convertMediaToJson(media));
            }
            if (!noPrimary) {
                dirty = establishDirtyState(newMedia, media);
                update = dirty;
            }
            if (dirty) {
                if (update) {
                    updateMedia(populateValueRequest, newMedia, persist, media);
                }
                response = MetadataProviderResponse.HANDLED_BREAK;
            }
        } else {
            throw new UnsupportedOperationException("MediaFields only work with Media types.");
        }
    } catch (Exception e) {
        throw ExceptionHelper.refineException(PersistenceException.class, PersistenceException.class, e);
    }
    populateValueRequest.getProperty().setIsDirty(dirty);
    return response;
}
Also used : Status(org.broadleafcommerce.common.persistence.Status) MetadataProviderResponse(org.broadleafcommerce.openadmin.server.service.type.MetadataProviderResponse) Media(org.broadleafcommerce.common.media.domain.Media) ExtensionResultStatusType(org.broadleafcommerce.common.extension.ExtensionResultStatusType) OneToMany(javax.persistence.OneToMany) FieldNotAvailableException(org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ParentEntityPersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.ParentEntityPersistenceException) PersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.PersistenceException) Field(java.lang.reflect.Field) FieldNotAvailableException(org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException) ParentEntityPersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.ParentEntityPersistenceException) PersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.PersistenceException) Tuple(org.broadleafcommerce.common.util.Tuple) ExtensionResultHolder(org.broadleafcommerce.common.extension.ExtensionResultHolder)

Example 3 with ExtensionResultStatusType

use of org.broadleafcommerce.common.extension.ExtensionResultStatusType in project BroadleafCommerce by BroadleafCommerce.

the class RuleFieldPersistenceProvider method populateSimpleRule.

protected boolean populateSimpleRule(PopulateValueRequest populateValueRequest, Serializable instance) throws Exception {
    boolean dirty = false;
    String prop = populateValueRequest.getProperty().getName();
    if (prop.contains(FieldManager.MAPFIELDSEPARATOR)) {
        Field field = populateValueRequest.getFieldManager().getField(instance.getClass(), prop.substring(0, prop.indexOf(FieldManager.MAPFIELDSEPARATOR)));
        if (field.getAnnotation(OneToMany.class) == null) {
            throw new UnsupportedOperationException("RuleFieldPersistenceProvider is currently only compatible with map fields when modelled using @OneToMany");
        }
    }
    DataDTOToMVELTranslator translator = new DataDTOToMVELTranslator();
    // AntiSamy HTML encodes the rule JSON - pass the unHTMLEncoded version
    DataWrapper dw = ruleFieldExtractionUtility.convertJsonToDataWrapper(populateValueRequest.getProperty().getUnHtmlEncodedValue());
    if (dw == null || StringUtils.isEmpty(dw.getError())) {
        String mvel = ruleFieldExtractionUtility.convertSimpleMatchRuleJsonToMvel(translator, RuleIdentifier.ENTITY_KEY_MAP.get(populateValueRequest.getMetadata().getRuleIdentifier()), populateValueRequest.getMetadata().getRuleIdentifier(), dw);
        Class<?> valueType = getStartingValueType(populateValueRequest);
        // This is a simple String field (or String map field)
        if (String.class.isAssignableFrom(valueType)) {
            // first check if the property is null and the mvel is null
            if (instance != null && mvel == null) {
                Object value = populateValueRequest.getFieldManager().getFieldValue(instance, populateValueRequest.getProperty().getName());
                dirty = value != null;
            } else {
                dirty = checkDirtyState(populateValueRequest, instance, mvel);
            }
            populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), mvel);
        }
        if (SimpleRule.class.isAssignableFrom(valueType)) {
            boolean persist = false;
            SimpleRule rule;
            try {
                rule = (SimpleRule) populateValueRequest.getFieldManager().getFieldValue(instance, populateValueRequest.getProperty().getName());
                if (rule == null) {
                    rule = (SimpleRule) valueType.newInstance();
                    Field field = populateValueRequest.getFieldManager().getField(instance.getClass(), prop.substring(0, prop.indexOf(FieldManager.MAPFIELDSEPARATOR)));
                    OneToMany oneToMany = field.getAnnotation(OneToMany.class);
                    Object parent = extractParent(populateValueRequest, instance);
                    populateValueRequest.getFieldManager().setFieldValue(rule, oneToMany.mappedBy(), parent);
                    populateValueRequest.getFieldManager().setFieldValue(rule, populateValueRequest.getMetadata().getMapKeyValueProperty(), prop.substring(prop.indexOf(FieldManager.MAPFIELDSEPARATOR) + FieldManager.MAPFIELDSEPARATOR.length(), prop.length()));
                    persist = true;
                }
            } catch (FieldNotAvailableException e) {
                throw new IllegalArgumentException(e);
            }
            if (mvel == null) {
                // cause the rule to be deleted
                dirty = populateValueRequest.getFieldManager().getFieldValue(instance, populateValueRequest.getProperty().getName()) != null;
                if (dirty) {
                    if (!populateValueRequest.getProperty().getName().contains(FieldManager.MAPFIELDSEPARATOR)) {
                        populateValueRequest.getFieldManager().setFieldValue(instance, populateValueRequest.getProperty().getName(), null);
                    } else {
                        // Since this class explicitly removes the simple rule - we must also preserve the id of the element
                        // as the CacheInvalidationProducer will need this in order to remove the member cache instance as well.
                        BroadleafRequestContext context = BroadleafRequestContext.getBroadleafRequestContext();
                        context.getAdditionalProperties().put("deletedSimpleRule", rule);
                        populateValueRequest.getPersistenceManager().getDynamicEntityDao().remove(rule);
                    }
                }
            } else if (rule != null) {
                dirty = !mvel.equals(rule.getMatchRule());
                if (!dirty && extensionManager != null) {
                    ExtensionResultHolder<Boolean> resultHolder = new ExtensionResultHolder<Boolean>();
                    ExtensionResultStatusType result = extensionManager.getProxy().establishDirtyState(rule, resultHolder);
                    if (ExtensionResultStatusType.NOT_HANDLED != result && resultHolder.getResult() != null) {
                        dirty = resultHolder.getResult();
                    }
                }
                if (dirty) {
                    updateSimpleRule(populateValueRequest, mvel, persist, rule);
                    EntityManager em = populateValueRequest.getPersistenceManager().getDynamicEntityDao().getStandardEntityManager();
                    Long id = getRuleId(rule, em);
                    Long containedId = getContainedRuleId(rule, em);
                    DataDTO dto = dw.getData().get(0);
                    if (persist && cascadeExtensionManager != null) {
                        ExtensionResultHolder resultHolder = new ExtensionResultHolder();
                        cascadeExtensionManager.getProxy().postCascadeAdd(rule, dto, resultHolder);
                    }
                    dto.setPk(id);
                    dto.setContainedPk(containedId);
                    ObjectMapper mapper = new ObjectMapper();
                    String json;
                    try {
                        json = mapper.writeValueAsString(dw);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    populateValueRequest.getProperty().setValue(json);
                }
            }
        }
    }
    return dirty;
}
Also used : BroadleafRequestContext(org.broadleafcommerce.common.web.BroadleafRequestContext) DataDTO(org.broadleafcommerce.openadmin.web.rulebuilder.dto.DataDTO) ExtensionResultStatusType(org.broadleafcommerce.common.extension.ExtensionResultStatusType) OneToMany(javax.persistence.OneToMany) DataDTOToMVELTranslator(org.broadleafcommerce.openadmin.web.rulebuilder.DataDTOToMVELTranslator) FieldNotAvailableException(org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException) MVELTranslationException(org.broadleafcommerce.openadmin.web.rulebuilder.MVELTranslationException) PersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.PersistenceException) ParentEntityPersistenceException(org.broadleafcommerce.openadmin.server.service.persistence.ParentEntityPersistenceException) DataWrapper(org.broadleafcommerce.openadmin.web.rulebuilder.dto.DataWrapper) Field(java.lang.reflect.Field) SimpleRule(org.broadleafcommerce.common.rule.SimpleRule) EntityManager(javax.persistence.EntityManager) FieldNotAvailableException(org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException) ExtensionResultHolder(org.broadleafcommerce.common.extension.ExtensionResultHolder) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 4 with ExtensionResultStatusType

use of org.broadleafcommerce.common.extension.ExtensionResultStatusType in project BroadleafCommerce by BroadleafCommerce.

the class MergeOrdersByEmailPostRegistrationObserver method processRegistrationEvent.

@Override
public void processRegistrationEvent(Customer customer) {
    List<Order> orders = orderService.findOrdersByEmail(customer.getEmailAddress());
    List<Order> updOrders = new ArrayList<>();
    for (Order o : orders) {
        if (!o.getCustomer().isRegistered()) {
            o.setCustomer(customer);
            updOrders.add(o);
        }
    }
    List<PostUpdateOrderExtensionHandler> handlers = extensionManager.getHandlers();
    for (PostUpdateOrderExtensionHandler h : handlers) {
        ExtensionResultStatusType status = h.postUpdateAll(updOrders);
        if (!extensionManager.shouldContinue(status, null, null, null)) {
            break;
        }
    }
}
Also used : Order(org.broadleafcommerce.core.order.domain.Order) ArrayList(java.util.ArrayList) ExtensionResultStatusType(org.broadleafcommerce.common.extension.ExtensionResultStatusType) PostUpdateOrderExtensionHandler(org.broadleafcommerce.core.order.extension.PostUpdateOrderExtensionHandler)

Example 5 with ExtensionResultStatusType

use of org.broadleafcommerce.common.extension.ExtensionResultStatusType in project BroadleafCommerce by BroadleafCommerce.

the class StaticAssetServiceImpl method createStaticAsset.

@Override
@Transactional(TransactionUtils.DEFAULT_TRANSACTION_MANAGER)
public StaticAsset createStaticAsset(InputStream inputStream, String fileName, long fileSize, Map<String, String> properties) {
    if (properties == null) {
        properties = new HashMap<String, String>();
    }
    String fullUrl = buildAssetURL(properties, fileName);
    StringBuilder urlBuilder = new StringBuilder();
    urlBuilder.append(fullUrl);
    ExtensionResultStatusType resultStatusType = staticAssetExtensionManager.getProxy().modifyDuplicateAssetURL(urlBuilder);
    fullUrl = urlBuilder.toString();
    StaticAsset newAsset = staticAssetDao.readStaticAssetByFullUrl(fullUrl);
    // logic for handling duplicate files.
    if (resultStatusType != ExtensionResultStatusType.HANDLED) {
        int count = 0;
        while (newAsset != null) {
            count++;
            // try the new format first, then the old
            newAsset = staticAssetDao.readStaticAssetByFullUrl(getCountUrl(fullUrl, count, false));
            if (newAsset == null) {
                newAsset = staticAssetDao.readStaticAssetByFullUrl(getCountUrl(fullUrl, count, true));
            }
        }
        if (count > 0) {
            fullUrl = getCountUrl(fullUrl, count, false);
        }
    }
    try {
        ImageMetadata metadata = imageArtifactProcessor.getImageMetadata(inputStream);
        newAsset = new ImageStaticAssetImpl();
        ((ImageStaticAsset) newAsset).setWidth(metadata.getWidth());
        ((ImageStaticAsset) newAsset).setHeight(metadata.getHeight());
    } catch (Exception e) {
        // must not be an image stream
        LOG.warn("unable to convert asset:" + fileName + " into Image");
        LOG.debug(e);
        if (getShouldAcceptNonImageAsset()) {
            newAsset = createNonImageAsset(inputStream, fileName, properties);
        } else {
            throw new RuntimeException("Selected Asset/File was not valid image.");
        }
    }
    if (storeAssetsOnFileSystem) {
        newAsset.setStorageType(StorageType.FILESYSTEM);
    } else {
        newAsset.setStorageType(StorageType.DATABASE);
    }
    newAsset.setName(fileName);
    getMimeType(inputStream, fileName, newAsset);
    newAsset.setFileExtension(getFileExtension(fileName));
    newAsset.setFileSize(fileSize);
    newAsset.setFullUrl(fullUrl);
    return staticAssetDao.addOrUpdateStaticAsset(newAsset, false);
}
Also used : ImageStaticAsset(org.broadleafcommerce.cms.file.domain.ImageStaticAsset) ImageMetadata(org.broadleafcommerce.openadmin.server.service.artifact.image.ImageMetadata) ImageStaticAsset(org.broadleafcommerce.cms.file.domain.ImageStaticAsset) StaticAsset(org.broadleafcommerce.cms.file.domain.StaticAsset) ExtensionResultStatusType(org.broadleafcommerce.common.extension.ExtensionResultStatusType) ImageStaticAssetImpl(org.broadleafcommerce.cms.file.domain.ImageStaticAssetImpl) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Transactional(org.springframework.transaction.annotation.Transactional)

Aggregations

ExtensionResultStatusType (org.broadleafcommerce.common.extension.ExtensionResultStatusType)59 ExtensionResultHolder (org.broadleafcommerce.common.extension.ExtensionResultHolder)35 ArrayList (java.util.ArrayList)11 Product (org.broadleafcommerce.core.catalog.domain.Product)9 Category (org.broadleafcommerce.core.catalog.domain.Category)7 BasicFieldMetadata (org.broadleafcommerce.openadmin.dto.BasicFieldMetadata)7 ServiceException (org.broadleafcommerce.common.exception.ServiceException)6 Sku (org.broadleafcommerce.core.catalog.domain.Sku)6 Entity (org.broadleafcommerce.openadmin.dto.Entity)6 FieldMetadata (org.broadleafcommerce.openadmin.dto.FieldMetadata)6 FieldNotAvailableException (org.broadleafcommerce.openadmin.server.service.persistence.module.FieldNotAvailableException)5 List (java.util.List)4 Query (javax.persistence.Query)4 TypedQuery (javax.persistence.TypedQuery)4 CriteriaQuery (javax.persistence.criteria.CriteriaQuery)4 IndexFieldType (org.broadleafcommerce.core.search.domain.IndexFieldType)4 PersistencePerspective (org.broadleafcommerce.openadmin.dto.PersistencePerspective)4 PersistenceException (org.broadleafcommerce.openadmin.server.service.persistence.PersistenceException)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 File (java.io.File)3