Search in sources :

Example 1 with StructuredContentType

use of org.broadleafcommerce.cms.structure.domain.StructuredContentType in project BroadleafCommerce by BroadleafCommerce.

the class StructuredContentServiceImpl method buildFieldValues.

/**
 * Parses the given {@link StructuredContent} into its {@link StructuredContentDTO} representation. This will also
 * format the values from {@link StructuredContentDTO#getValues()} into their actual data types. For instance, if the
 * given {@link StructuredContent} has a DATE field, then this method will ensure that the resulting object in the values
 * map of the DTO is a {@link Date} rather than just a String representing a date.
 * <p/>
 * Current support of parsing field types is:
 * DATE - {@link Date}
 * BOOLEAN - {@link Boolean}
 * DECIMAL - {@link BigDecimal}
 * INTEGER - {@link Integer}
 * MONEY - {@link Money}
 * <p/>
 * All other fields are treated as strings. This will also fix URL strings that have the CMS prefix (like images) by
 * prepending the standard CMS prefix with the particular environment prefix
 *
 * @param sc
 * @param scDTO
 * @param secure
 * @see {@link StaticAssetService#getStaticAssetEnvironmentUrlPrefix()}
 */
protected void buildFieldValues(StructuredContent sc, StructuredContentDTO scDTO, boolean secure) {
    String cmsPrefix = staticAssetPathService.getStaticAssetUrlPrefix();
    Map<String, StructuredContentFieldXref> scFieldXrefs = MapUtils.emptyIfNull(sc.getStructuredContentFieldXrefs());
    scDTO.getValues().put("id", sc.getId());
    for (String fieldKey : scFieldXrefs.keySet()) {
        StructuredContentField scf = scFieldXrefs.get(fieldKey).getStructuredContentField();
        String originalValue = scf.getValue();
        if (hasCmsPrefix(originalValue, cmsPrefix)) {
            buildFieldValueWithCmsPrefix(originalValue, scDTO, secure, fieldKey);
        } else {
            FieldDefinition definition = null;
            StructuredContentType scType = sc.getStructuredContentType();
            StructuredContentFieldTemplate scFieldTemplate = scType.getStructuredContentFieldTemplate();
            List<FieldGroup> scFieldGroups = ListUtils.emptyIfNull(scFieldTemplate.getFieldGroups());
            Iterator<FieldGroup> groupIterator = scFieldGroups.iterator();
            while (groupIterator.hasNext() && definition == null) {
                FieldGroup group = groupIterator.next();
                for (FieldDefinition def : group.getFieldDefinitions()) {
                    if (def.getName().equals(fieldKey)) {
                        definition = def;
                        break;
                    }
                }
            }
            if (definition != null) {
                Object value = null;
                if (originalValue != null) {
                    switch(definition.getFieldType()) {
                        case DATE:
                            try {
                                value = FormatUtil.getDateFormat().parse(originalValue);
                            } catch (Exception e) {
                                value = originalValue;
                            }
                            break;
                        case BOOLEAN:
                            value = new Boolean(originalValue);
                            break;
                        case DECIMAL:
                            value = new BigDecimal(originalValue);
                            break;
                        case INTEGER:
                            value = Integer.parseInt(originalValue);
                            break;
                        case MONEY:
                            value = new Money(originalValue);
                            break;
                        case ADDITIONAL_FOREIGN_KEY:
                            value = FOREIGN_LOOKUP + '|' + definition.getAdditionalForeignKeyClass() + '|' + originalValue;
                            break;
                        default:
                            value = originalValue;
                            break;
                    }
                }
                scDTO.getValues().put(fieldKey, value);
            } else {
                scDTO.getValues().put(fieldKey, scFieldXrefs.get(fieldKey).getStructuredContentField().getValue());
            }
        }
    }
    // allow modules to contribute to the fields of the DTO
    extensionManager.getProxy().populateAdditionalStructuredContentFields(sc, scDTO, secure);
}
Also used : FieldGroup(org.broadleafcommerce.cms.field.domain.FieldGroup) FieldDefinition(org.broadleafcommerce.cms.field.domain.FieldDefinition) BigDecimal(java.math.BigDecimal) StructuredContentFieldTemplate(org.broadleafcommerce.cms.structure.domain.StructuredContentFieldTemplate) Money(org.broadleafcommerce.common.money.Money) StructuredContentField(org.broadleafcommerce.cms.structure.domain.StructuredContentField) StructuredContentType(org.broadleafcommerce.cms.structure.domain.StructuredContentType) StructuredContentFieldXref(org.broadleafcommerce.cms.structure.domain.StructuredContentFieldXref)

Example 2 with StructuredContentType

use of org.broadleafcommerce.cms.structure.domain.StructuredContentType in project BroadleafCommerce by BroadleafCommerce.

the class ContentProcessor method populateModelVariables.

@Override
public Map<String, Object> populateModelVariables(String tagName, Map<String, String> tagAttributes, BroadleafTemplateContext context) {
    String contentType = tagAttributes.get("contentType");
    String contentName = tagAttributes.get("contentName");
    String maxResultsStr = tagAttributes.get("maxResults");
    if (StringUtils.isEmpty(contentType) && StringUtils.isEmpty(contentName)) {
        throw new IllegalArgumentException("The content processor must have a non-empty attribute value for 'contentType' or 'contentName'");
    }
    Integer maxResults = null;
    if (maxResultsStr != null) {
        maxResults = Ints.tryParse(maxResultsStr);
    }
    if (maxResults == null) {
        maxResults = Integer.MAX_VALUE;
    }
    String contentListVar = getAttributeValue(tagAttributes, "contentListVar", "contentList");
    String contentItemVar = getAttributeValue(tagAttributes, "contentItemVar", "contentItem");
    String numResultsVar = getAttributeValue(tagAttributes, "numResultsVar", "numResults");
    String fieldFilters = tagAttributes.get("fieldFilters");
    final String sorts = tagAttributes.get("sorts");
    BroadleafRequestContext blcContext = BroadleafRequestContext.getBroadleafRequestContext();
    HttpServletRequest request = blcContext.getRequest();
    Map<String, Object> mvelParameters = buildMvelParameters(blcContext.getRequest(), tagAttributes, context);
    SandBox currentSandbox = blcContext.getSandBox();
    List<StructuredContentDTO> contentItems;
    StructuredContentType structuredContentType = null;
    if (contentType != null) {
        structuredContentType = structuredContentService.findStructuredContentTypeByName(contentType);
    }
    Locale locale = blcContext.getLocale();
    Map<String, Object> newModelVars = new HashMap<>();
    contentItems = getContentItems(contentName, maxResults, request, mvelParameters, currentSandbox, structuredContentType, locale, tagName, tagAttributes, newModelVars, context);
    if (contentItems.size() > 0) {
        // sort the resulting list by the configured property sorts on the tag
        if (StringUtils.isNotEmpty(sorts)) {
            final BroadleafTemplateContext finalContext = context;
            // In order to use the context in a comparator it needs to be final
            Collections.sort(contentItems, new Comparator<StructuredContentDTO>() {

                @Override
                public int compare(StructuredContentDTO o1, StructuredContentDTO o2) {
                    List<BroadleafAssignation> sortAssignments = finalContext.getAssignationSequence(sorts, false);
                    CompareToBuilder compareBuilder = new CompareToBuilder();
                    for (BroadleafAssignation sortAssignment : sortAssignments) {
                        String property = sortAssignment.getLeftStringRepresentation(finalContext);
                        Object val1 = o1.getPropertyValue(property);
                        Object val2 = o2.getPropertyValue(property);
                        if (sortAssignment.parseRight(finalContext).equals("ASCENDING")) {
                            compareBuilder.append(val1, val2);
                        } else {
                            compareBuilder.append(val2, val1);
                        }
                    }
                    return compareBuilder.toComparison();
                }
            });
        }
        List<Map<String, Object>> contentItemFields = new ArrayList<>();
        for (StructuredContentDTO item : contentItems) {
            if (StringUtils.isNotEmpty(fieldFilters)) {
                List<BroadleafAssignation> assignments = context.getAssignationSequence(fieldFilters, false);
                boolean valid = true;
                for (BroadleafAssignation assignment : assignments) {
                    if (ObjectUtils.notEqual(assignment.parseRight(context), item.getValues().get(assignment.getLeftStringRepresentation(context)))) {
                        LOG.info("Excluding content " + item.getId() + " based on the property value of " + assignment.getLeftStringRepresentation(context));
                        valid = false;
                        break;
                    }
                }
                if (valid) {
                    contentItemFields.add(item.getValues());
                }
            } else {
                contentItemFields.add(item.getValues());
            }
        }
        Map<String, Object> contentItem = null;
        if (contentItemFields.size() > 0) {
            contentItem = contentItemFields.get(0);
        }
        newModelVars.put(contentItemVar, contentItem);
        newModelVars.put(contentListVar, contentItemFields);
        newModelVars.put(numResultsVar, contentItems.size());
    } else {
        if (LOG.isInfoEnabled()) {
            LOG.info("**************************The contentItems is null*************************");
        }
        newModelVars.put(contentItemVar, null);
        newModelVars.put(contentListVar, null);
        newModelVars.put(numResultsVar, 0);
    }
    String deepLinksVar = tagAttributes.get("deepLinks");
    if (StringUtils.isNotBlank(deepLinksVar) && contentItems.size() > 0) {
        List<DeepLink> links = contentDeepLinkService.getLinks(contentItems.get(0));
        extensionManager.getProxy().addExtensionFieldDeepLink(links, tagName, tagAttributes, context);
        extensionManager.getProxy().postProcessDeepLinks(links);
        newModelVars.put(deepLinksVar, links);
    }
    return newModelVars;
}
Also used : Locale(org.broadleafcommerce.common.locale.domain.Locale) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) HttpServletRequest(javax.servlet.http.HttpServletRequest) ArrayList(java.util.ArrayList) List(java.util.List) CompareToBuilder(org.apache.commons.lang3.builder.CompareToBuilder) BroadleafTemplateContext(org.broadleafcommerce.presentation.model.BroadleafTemplateContext) SandBox(org.broadleafcommerce.common.sandbox.domain.SandBox) StructuredContentDTO(org.broadleafcommerce.common.structure.dto.StructuredContentDTO) BroadleafRequestContext(org.broadleafcommerce.common.web.BroadleafRequestContext) DeepLink(org.broadleafcommerce.common.web.deeplink.DeepLink) StructuredContentType(org.broadleafcommerce.cms.structure.domain.StructuredContentType) BroadleafAssignation(org.broadleafcommerce.presentation.model.BroadleafAssignation) HashMap(java.util.HashMap) Map(java.util.Map)

Example 3 with StructuredContentType

use of org.broadleafcommerce.cms.structure.domain.StructuredContentType in project BroadleafCommerce by BroadleafCommerce.

the class StructuredContentDaoImpl method findStructuredContentTypeByName.

@Override
public StructuredContentType findStructuredContentTypeByName(String name) {
    Query query = em.createNamedQuery("BC_READ_STRUCTURED_CONTENT_TYPE_BY_NAME");
    query.setParameter("name", name);
    query.setHint(QueryHints.HINT_CACHEABLE, true);
    List<StructuredContentType> results = query.getResultList();
    if (results.size() > 0) {
        return results.get(0);
    } else {
        return null;
    }
}
Also used : CriteriaQuery(javax.persistence.criteria.CriteriaQuery) TypedQuery(javax.persistence.TypedQuery) Query(javax.persistence.Query) StructuredContentType(org.broadleafcommerce.cms.structure.domain.StructuredContentType)

Example 4 with StructuredContentType

use of org.broadleafcommerce.cms.structure.domain.StructuredContentType in project BroadleafCommerce by BroadleafCommerce.

the class StructuredContentTypeCustomPersistenceHandler method inspect.

@Override
public DynamicResultSet inspect(PersistencePackage persistencePackage, DynamicEntityDao dynamicEntityDao, InspectHelper helper) throws ServiceException {
    String ceilingEntityFullyQualifiedClassname = persistencePackage.getCeilingEntityFullyQualifiedClassname();
    try {
        String structuredContentTypeId = persistencePackage.getCustomCriteria()[3];
        StructuredContentType structuredContentType = structuredContentService.findStructuredContentTypeById(Long.valueOf(structuredContentTypeId));
        ClassMetadata metadata = new ClassMetadata();
        metadata.setCeilingType(StructuredContentType.class.getName());
        ClassTree entities = new ClassTree(StructuredContentTypeImpl.class.getName());
        metadata.setPolymorphicEntities(entities);
        Property[] properties = dynamicFieldUtil.buildDynamicPropertyList(structuredContentType.getStructuredContentFieldTemplate().getFieldGroups(), StructuredContentTypeImpl.class);
        metadata.setProperties(properties);
        DynamicResultSet results = new DynamicResultSet(metadata);
        return results;
    } catch (Exception e) {
        throw new ServiceException("Unable to perform inspect for entity: " + ceilingEntityFullyQualifiedClassname, e);
    }
}
Also used : ClassMetadata(org.broadleafcommerce.openadmin.dto.ClassMetadata) StructuredContentTypeImpl(org.broadleafcommerce.cms.structure.domain.StructuredContentTypeImpl) ServiceException(org.broadleafcommerce.common.exception.ServiceException) ClassTree(org.broadleafcommerce.openadmin.dto.ClassTree) StructuredContentType(org.broadleafcommerce.cms.structure.domain.StructuredContentType) Property(org.broadleafcommerce.openadmin.dto.Property) DynamicResultSet(org.broadleafcommerce.openadmin.dto.DynamicResultSet) ServiceException(org.broadleafcommerce.common.exception.ServiceException) ValidationException(org.broadleafcommerce.openadmin.server.service.ValidationException)

Example 5 with StructuredContentType

use of org.broadleafcommerce.cms.structure.domain.StructuredContentType in project BroadleafCommerce by BroadleafCommerce.

the class AdminStructuredContentController method viewEntityForm.

@Override
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public String viewEntityForm(HttpServletRequest request, HttpServletResponse response, Model model, @PathVariable Map<String, String> pathVars, @PathVariable(value = "id") String id) throws Exception {
    // Get the normal entity form for this item
    String returnPath = super.viewEntityForm(request, response, model, pathVars, id);
    EntityForm ef = (EntityForm) model.asMap().get("entityForm");
    // Attach the dynamic fields to the form
    DynamicEntityFormInfo info = new DynamicEntityFormInfo().withCeilingClassName(StructuredContentType.class.getName()).withSecurityCeilingClassName(StructuredContent.class.getName()).withCriteriaName("constructForm").withPropertyName("structuredContentType").withPropertyValue(ef.findField("structuredContentType").getValue());
    EntityForm dynamicForm = getDynamicFieldTemplateForm(info, id, null);
    ef.putDynamicFormInfo("structuredContentType", info);
    ef.putDynamicForm("structuredContentType", dynamicForm);
    // We don't want to allow changing types once a structured content item exists
    ef.findField("structuredContentType").setReadOnly(true);
    return returnPath;
}
Also used : EntityForm(org.broadleafcommerce.openadmin.web.form.entity.EntityForm) StructuredContentType(org.broadleafcommerce.cms.structure.domain.StructuredContentType) DynamicEntityFormInfo(org.broadleafcommerce.openadmin.web.form.entity.DynamicEntityFormInfo) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

StructuredContentType (org.broadleafcommerce.cms.structure.domain.StructuredContentType)5 BigDecimal (java.math.BigDecimal)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 List (java.util.List)1 Map (java.util.Map)1 Query (javax.persistence.Query)1 TypedQuery (javax.persistence.TypedQuery)1 CriteriaQuery (javax.persistence.criteria.CriteriaQuery)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 CompareToBuilder (org.apache.commons.lang3.builder.CompareToBuilder)1 FieldDefinition (org.broadleafcommerce.cms.field.domain.FieldDefinition)1 FieldGroup (org.broadleafcommerce.cms.field.domain.FieldGroup)1 StructuredContentField (org.broadleafcommerce.cms.structure.domain.StructuredContentField)1 StructuredContentFieldTemplate (org.broadleafcommerce.cms.structure.domain.StructuredContentFieldTemplate)1 StructuredContentFieldXref (org.broadleafcommerce.cms.structure.domain.StructuredContentFieldXref)1 StructuredContentTypeImpl (org.broadleafcommerce.cms.structure.domain.StructuredContentTypeImpl)1 ServiceException (org.broadleafcommerce.common.exception.ServiceException)1 Locale (org.broadleafcommerce.common.locale.domain.Locale)1 Money (org.broadleafcommerce.common.money.Money)1