Search in sources :

Example 6 with BroadleafRequestContext

use of org.broadleafcommerce.common.web.BroadleafRequestContext in project BroadleafCommerce by BroadleafCommerce.

the class BasicPersistenceModule method getDecimalFormatter.

@Override
public DecimalFormat getDecimalFormatter() {
    BroadleafRequestContext brc = BroadleafRequestContext.getBroadleafRequestContext();
    Locale locale = brc.getJavaLocale();
    DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(locale);
    format.applyPattern("0.########");
    format.setGroupingUsed(false);
    return format;
}
Also used : Locale(java.util.Locale) BroadleafRequestContext(org.broadleafcommerce.common.web.BroadleafRequestContext) DecimalFormat(java.text.DecimalFormat)

Example 7 with BroadleafRequestContext

use of org.broadleafcommerce.common.web.BroadleafRequestContext 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 8 with BroadleafRequestContext

use of org.broadleafcommerce.common.web.BroadleafRequestContext in project BroadleafCommerce by BroadleafCommerce.

the class MapStructurePersistenceModule method procureSandBoxMapValue.

protected Serializable procureSandBoxMapValue(MapStructure mapStructure, Entity entity) {
    try {
        Serializable valueInstance = null;
        // this is probably a sync from another sandbox where they've updated a map item for which we've updated the key in our own sandbox
        // (i.e. the map entry key was changed by us in our sandbox, so our map does not have the requested key)
        Class<?> valueClass = Class.forName(mapStructure.getValueClassName());
        Map<String, Object> idMetadata = getPersistenceManager().getDynamicEntityDao().getIdMetadata(valueClass);
        String idProperty = (String) idMetadata.get("name");
        Property prop = entity.findProperty(idProperty);
        if (prop != null) {
            Serializable identifier;
            if (!(((Type) idMetadata.get("type")) instanceof StringType)) {
                identifier = Long.parseLong(prop.getValue());
            } else {
                identifier = prop.getValue();
            }
            valueInstance = (Serializable) getPersistenceManager().getDynamicEntityDao().find(valueClass, identifier);
            BroadleafRequestContext context = BroadleafRequestContext.getBroadleafRequestContext();
            if (sandBoxHelper.isSandBoxable(valueInstance.getClass().getName()) && context != null && !context.isProductionSandBox()) {
                if (sandBoxHelper.isPromote() && !sandBoxHelper.isReject()) {
                    // if this is a prod record (i.e. the destination map has deleted our record), then duplicate our value
                    // so it's available in this sandbox
                    valueInstance = getPersistenceManager().getDynamicEntityDao().merge(valueInstance);
                } else {
                    valueInstance = null;
                }
            }
        }
        return valueInstance;
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
}
Also used : Serializable(java.io.Serializable) MergedPropertyType(org.broadleafcommerce.openadmin.dto.MergedPropertyType) OperationType(org.broadleafcommerce.common.presentation.client.OperationType) PersistencePerspectiveItemType(org.broadleafcommerce.common.presentation.client.PersistencePerspectiveItemType) StringType(org.hibernate.type.StringType) Type(org.hibernate.type.Type) StringType(org.hibernate.type.StringType) BroadleafRequestContext(org.broadleafcommerce.common.web.BroadleafRequestContext) CriteriaTransferObject(org.broadleafcommerce.openadmin.dto.CriteriaTransferObject) Property(org.broadleafcommerce.openadmin.dto.Property)

Example 9 with BroadleafRequestContext

use of org.broadleafcommerce.common.web.BroadleafRequestContext in project BroadleafCommerce by BroadleafCommerce.

the class FieldLengthValidator method validate.

@Override
public PropertyValidationResult validate(Entity entity, Serializable instance, Map<String, FieldMetadata> entityFieldMetadata, BasicFieldMetadata propertyMetadata, String propertyName, String value) {
    boolean valid = true;
    String errorMessage = "";
    if (propertyMetadata.getLength() != null) {
        valid = StringUtils.length(value) <= propertyMetadata.getLength();
    }
    if (!valid) {
        BroadleafRequestContext context = BroadleafRequestContext.getBroadleafRequestContext();
        MessageSource messages = context.getMessageSource();
        errorMessage = messages.getMessage("fieldLengthValidationFailure", new Object[] { propertyMetadata.getLength(), StringUtils.length(value) }, context.getJavaLocale());
    }
    return new PropertyValidationResult(valid, errorMessage);
}
Also used : BroadleafRequestContext(org.broadleafcommerce.common.web.BroadleafRequestContext) MessageSource(org.springframework.context.MessageSource)

Example 10 with BroadleafRequestContext

use of org.broadleafcommerce.common.web.BroadleafRequestContext in project BroadleafCommerce by BroadleafCommerce.

the class BroadleafContextUtil method establishThinRequestContextInternal.

/**
 * Adds request and site to the BroadleafRequestContext
 *
 * If includeTheme is true then also adds the Theme.
 * If includeSandBox is true then also adds the SandBox.
 *
 * @param includeTheme
 * @param includeSandBox
 */
protected void establishThinRequestContextInternal(boolean includeTheme, boolean includeSandBox) {
    BroadleafRequestContext brc = BroadleafRequestContext.getBroadleafRequestContext();
    if (brc.getRequest() == null) {
        HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = req.getSession(false);
        SecurityContext ctx = readSecurityContextFromSession(session);
        if (ctx != null) {
            SecurityContextHolder.setContext(ctx);
        }
        brc.setRequest(req);
    }
    WebRequest wr = brc.getWebRequest();
    if (brc.getNonPersistentSite() == null) {
        brc.setNonPersistentSite(siteResolver.resolveSite(wr, true));
        if (includeSandBox) {
            brc.setSandBox(sbResolver.resolveSandBox(wr, brc.getNonPersistentSite()));
        }
        brc.setDeployBehavior(deployBehaviorUtil.isProductionSandBoxMode() ? DeployBehavior.CLONE_PARENT : DeployBehavior.OVERWRITE_PARENT);
    }
    if (includeTheme) {
        if (brc.getTheme() == null) {
            brc.setTheme(themeResolver.resolveTheme(wr));
        }
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) WebRequest(org.springframework.web.context.request.WebRequest) BroadleafRequestContext(org.broadleafcommerce.common.web.BroadleafRequestContext) HttpSession(javax.servlet.http.HttpSession) ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) SecurityContext(org.springframework.security.core.context.SecurityContext)

Aggregations

BroadleafRequestContext (org.broadleafcommerce.common.web.BroadleafRequestContext)78 Site (org.broadleafcommerce.common.site.domain.Site)16 HashMap (java.util.HashMap)12 HttpServletRequest (javax.servlet.http.HttpServletRequest)11 ArrayList (java.util.ArrayList)9 Map (java.util.Map)9 Locale (org.broadleafcommerce.common.locale.domain.Locale)8 SandBox (org.broadleafcommerce.common.sandbox.domain.SandBox)5 StructuredContentDTO (org.broadleafcommerce.common.structure.dto.StructuredContentDTO)5 MessageSource (org.springframework.context.MessageSource)5 List (java.util.List)4 StructuredContent (org.broadleafcommerce.cms.structure.domain.StructuredContent)4 Field (java.lang.reflect.Field)3 HashSet (java.util.HashSet)3 Locale (java.util.Locale)3 Catalog (org.broadleafcommerce.common.site.domain.Catalog)3 BroadleafAttributeModifier (org.broadleafcommerce.presentation.model.BroadleafAttributeModifier)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 File (java.io.File)2 PrintWriter (java.io.PrintWriter)2