public void deleteCategory(AssetCategory category) throws PortalException, SystemException {

    // Category

    assetCategoryPersistence.remove(category);

    // Resources

    resourceLocalService.deleteResource(
        category.getCompanyId(),
        AssetCategory.class.getName(),
        ResourceConstants.SCOPE_INDIVIDUAL,
        category.getCategoryId());

    // Categories

    List<AssetCategory> categories =
        assetCategoryPersistence.findByParentCategoryId(category.getCategoryId());

    for (AssetCategory curCategory : categories) {
      deleteCategory(curCategory);
    }

    // Properties

    assetCategoryPropertyLocalService.deleteCategoryProperties(category.getCategoryId());
  }
  protected void assertLeftAndRight(
      AssetCategory assetCategory, long leftCategoryId, long rightCategoryId) {

    Assert.assertEquals(leftCategoryId, assetCategory.getLeftCategoryId());
    Assert.assertEquals(rightCategoryId, assetCategory.getRightCategoryId());

    _assetCategoryPersistence.update(assetCategory);
  }
  @Override
  protected void doReindex(Object obj) throws Exception {
    AssetCategory category = (AssetCategory) obj;

    Document document = getDocument(category);

    if (document != null) {
      SearchEngineUtil.updateDocument(getSearchEngineId(), category.getCompanyId(), document);
    }
  }
  @Override
  protected void doDelete(Object obj) throws Exception {
    AssetCategory assetCategory = (AssetCategory) obj;

    Document document = new DocumentImpl();

    document.addUID(PORTLET_ID, assetCategory.getCategoryId());

    SearchEngineUtil.deleteDocument(
        getSearchEngineId(), assetCategory.getCompanyId(), document.get(Field.UID));
  }
  public void addCategoryResources(
      AssetCategory category, String[] communityPermissions, String[] guestPermissions)
      throws PortalException, SystemException {

    resourceLocalService.addModelResources(
        category.getCompanyId(),
        category.getGroupId(),
        category.getUserId(),
        AssetCategory.class.getName(),
        category.getCategoryId(),
        communityPermissions,
        guestPermissions);
  }
  protected ServiceContext createServiceContext(
      PortletDataContext portletDataContext, AssetCategory category) {

    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setAddGroupPermissions(true);
    serviceContext.setAddGuestPermissions(true);
    serviceContext.setCreateDate(category.getCreateDate());
    serviceContext.setModifiedDate(category.getModifiedDate());
    serviceContext.setScopeGroupId(portletDataContext.getScopeGroupId());

    return serviceContext;
  }
  public void addCategoryResources(
      AssetCategory category, boolean addCommunityPermissions, boolean addGuestPermissions)
      throws PortalException, SystemException {

    resourceLocalService.addResources(
        category.getCompanyId(),
        category.getGroupId(),
        category.getUserId(),
        AssetCategory.class.getName(),
        category.getCategoryId(),
        false,
        addCommunityPermissions,
        addGuestPermissions);
  }
  protected String getCategoryName(
      String uuid, long groupId, long parentCategoryId, String name, long vocabularyId, int count)
      throws Exception {

    AssetCategory category =
        AssetCategoryUtil.fetchByG_P_N_V_First(groupId, parentCategoryId, name, vocabularyId, null);

    if ((category == null) || (Validator.isNotNull(uuid) && uuid.equals(category.getUuid()))) {

      return name;
    }

    name = StringUtil.appendParentheticalSuffix(name, count);

    return getCategoryName(uuid, groupId, parentCategoryId, name, vocabularyId, ++count);
  }
  protected void updateChildrenVocabularyId(AssetCategory category, long vocabularyId)
      throws SystemException {

    List<AssetCategory> childrenCategories =
        assetCategoryPersistence.findByParentCategoryId(category.getCategoryId());

    if (!childrenCategories.isEmpty()) {
      for (AssetCategory childCategory : childrenCategories) {
        childCategory.setVocabularyId(vocabularyId);
        childCategory.setModifiedDate(new Date());

        assetCategoryPersistence.update(childCategory);

        updateChildrenVocabularyId(childCategory, vocabularyId);
      }
    }
  }
  @Override
  public void addUserAttributes(
      User user, String[] customUserAttributeNames, AssetEntryQuery assetEntryQuery)
      throws Exception {

    if ((user == null) || (customUserAttributeNames.length == 0)) {
      return;
    }

    Group companyGroup = GroupLocalServiceUtil.getCompanyGroup(user.getCompanyId());

    long[] allCategoryIds = assetEntryQuery.getAllCategoryIds();

    PrimitiveLongList allCategoryIdsList =
        new PrimitiveLongList(allCategoryIds.length + customUserAttributeNames.length);

    allCategoryIdsList.addAll(allCategoryIds);

    for (String customUserAttributeName : customUserAttributeNames) {
      ExpandoBridge userCustomAttributes = user.getExpandoBridge();

      Serializable userCustomFieldValue =
          userCustomAttributes.getAttribute(customUserAttributeName);

      if (userCustomFieldValue == null) {
        continue;
      }

      String userCustomFieldValueString = userCustomFieldValue.toString();

      List<AssetCategory> assetCategories =
          AssetCategoryLocalServiceUtil.search(
              companyGroup.getGroupId(),
              userCustomFieldValueString,
              new String[0],
              QueryUtil.ALL_POS,
              QueryUtil.ALL_POS);

      for (AssetCategory assetCategory : assetCategories) {
        allCategoryIdsList.add(assetCategory.getCategoryId());
      }
    }

    assetEntryQuery.setAllCategoryIds(allCategoryIdsList.getArray());
  }
Ejemplo n.º 11
0
  protected Map<Locale, String> getAssetCategoryTitleMap(AssetCategory assetCategory) {

    Map<Locale, String> titleMap = assetCategory.getTitleMap();

    if (titleMap == null) {
      titleMap = new HashMap<Locale, String>();
    }

    Locale locale = LocaleUtil.getDefault();

    String title = titleMap.get(locale);

    if (Validator.isNull(title)) {
      titleMap.put(locale, assetCategory.getName());
    }

    return titleMap;
  }
  protected void validate(long categoryId, long parentCategoryId, String name, long vocabularyId)
      throws PortalException, SystemException {

    if (Validator.isNull(name)) {
      throw new AssetCategoryNameException();
    }

    AssetCategory category =
        assetCategoryPersistence.fetchByP_N_V(parentCategoryId, name, vocabularyId);

    if ((category != null) && (category.getCategoryId() != categoryId)) {
      StringBundler sb = new StringBundler(4);

      sb.append("There is another category named ");
      sb.append(name);
      sb.append(" as a child of category ");
      sb.append(parentCategoryId);

      throw new DuplicateCategoryException(sb.toString());
    }
  }
  @Indexable(type = IndexableType.REINDEX)
  @Override
  public AssetCategory moveCategory(
      long categoryId, long parentCategoryId, long vocabularyId, ServiceContext serviceContext)
      throws PortalException, SystemException {

    AssetCategory category = assetCategoryPersistence.findByPrimaryKey(categoryId);

    validate(categoryId, parentCategoryId, category.getName(), vocabularyId);

    if (parentCategoryId > 0) {
      assetCategoryPersistence.findByPrimaryKey(parentCategoryId);
    }

    if (vocabularyId != category.getVocabularyId()) {
      assetVocabularyPersistence.findByPrimaryKey(vocabularyId);

      category.setVocabularyId(vocabularyId);

      updateChildrenVocabularyId(category, vocabularyId);
    }

    category.setModifiedDate(new Date());
    category.setParentCategoryId(parentCategoryId);

    assetCategoryPersistence.update(category);

    return category;
  }
  protected Map<Locale, String> getCategoryTitleMap(
      long groupId, AssetCategory category, String name) throws PortalException, SystemException {

    Map<Locale, String> titleMap = category.getTitleMap();

    if (titleMap == null) {
      titleMap = new HashMap<Locale, String>();
    }

    titleMap.put(PortalUtil.getSiteDefaultLocale(groupId), name);

    return titleMap;
  }
Ejemplo n.º 15
0
  protected void exportAssetCategory(
      PortletDataContext portletDataContext,
      Element assetVocabulariesElement,
      Element assetCategoriesElement,
      AssetCategory assetCategory)
      throws Exception {

    exportAssetVocabulary(
        portletDataContext, assetVocabulariesElement, assetCategory.getVocabularyId());

    if (assetCategory.getParentCategoryId() != AssetCategoryConstants.DEFAULT_PARENT_CATEGORY_ID) {

      exportAssetCategory(
          portletDataContext,
          assetVocabulariesElement,
          assetCategoriesElement,
          assetCategory.getParentCategoryId());
    }

    String path = getAssetCategoryPath(portletDataContext, assetCategory.getCategoryId());

    if (!portletDataContext.isPathNotProcessed(path)) {
      return;
    }

    Element assetCategoryElement = assetCategoriesElement.addElement("category");

    assetCategoryElement.addAttribute("path", path);

    assetCategory.setUserUuid(assetCategory.getUserUuid());

    portletDataContext.addZipEntry(path, assetCategory);

    List<AssetCategoryProperty> assetCategoryProperties =
        AssetCategoryPropertyLocalServiceUtil.getCategoryProperties(assetCategory.getCategoryId());

    for (AssetCategoryProperty assetCategoryProperty : assetCategoryProperties) {

      Element propertyElement = assetCategoryElement.addElement("property");

      propertyElement.addAttribute("userUuid", assetCategoryProperty.getUserUuid());
      propertyElement.addAttribute("key", assetCategoryProperty.getKey());
      propertyElement.addAttribute("value", assetCategoryProperty.getValue());
    }

    portletDataContext.addPermissions(AssetCategory.class, assetCategory.getCategoryId());
  }
  @Indexable(type = IndexableType.DELETE)
  @Override
  public AssetCategory deleteCategory(AssetCategory category, boolean childCategory)
      throws PortalException, SystemException {

    // Categories

    List<AssetCategory> categories =
        assetCategoryPersistence.findByParentCategoryId(category.getCategoryId());

    for (AssetCategory curCategory : categories) {
      deleteCategory(curCategory, true);
    }

    if (!categories.isEmpty() && !childCategory) {
      final long groupId = category.getGroupId();

      TransactionCommitCallbackRegistryUtil.registerCallback(
          new Callable<Void>() {

            @Override
            public Void call() throws Exception {
              assetCategoryLocalService.rebuildTree(groupId, true);

              return null;
            }
          });
    }

    // Category

    assetCategoryPersistence.remove(category);

    // Resources

    resourceLocalService.deleteResource(
        category.getCompanyId(),
        AssetCategory.class.getName(),
        ResourceConstants.SCOPE_INDIVIDUAL,
        category.getCategoryId());

    // Entries

    List<AssetEntry> entries = assetTagPersistence.getAssetEntries(category.getCategoryId());

    // Properties

    assetCategoryPropertyLocalService.deleteCategoryProperties(category.getCategoryId());

    // Indexer

    assetEntryLocalService.reindex(entries);

    return category;
  }
  protected void synchronizeAssetCategories(AssetCategory assetCategory, boolean delete) {

    if (assetCategory != null) {
      if (delete) {
        _assetCategoryPersistence.remove(assetCategory);
      } else {
        _assetCategoryPersistence.update(assetCategory);
      }
    }

    _assetCategoryPersistence.clearCache();

    for (int i = 0; i < _assetCategories.length; i++) {
      assetCategory = _assetCategories[i];

      if (assetCategory != null) {
        _assetCategories[i] =
            _assetCategoryPersistence.fetchByPrimaryKey(assetCategory.getCategoryId());
      }
    }
  }
  @Override
  protected void doExportStagedModel(PortletDataContext portletDataContext, AssetCategory category)
      throws Exception {

    if (category.getParentCategoryId() != AssetCategoryConstants.DEFAULT_PARENT_CATEGORY_ID) {

      AssetCategory parentCategory =
          AssetCategoryLocalServiceUtil.fetchAssetCategory(category.getParentCategoryId());

      StagedModelDataHandlerUtil.exportReferenceStagedModel(
          portletDataContext, category, parentCategory, PortletDataContext.REFERENCE_TYPE_PARENT);
    } else {
      AssetVocabulary vocabulary =
          AssetVocabularyLocalServiceUtil.fetchAssetVocabulary(category.getVocabularyId());

      StagedModelDataHandlerUtil.exportReferenceStagedModel(
          portletDataContext, category, vocabulary, PortletDataContext.REFERENCE_TYPE_PARENT);
    }

    Element categoryElement = portletDataContext.getExportDataElement(category);

    category.setUserUuid(category.getUserUuid());

    List<AssetCategoryProperty> categoryProperties =
        AssetCategoryPropertyLocalServiceUtil.getCategoryProperties(category.getCategoryId());

    for (AssetCategoryProperty categoryProperty : categoryProperties) {
      Element propertyElement = categoryElement.addElement("property");

      propertyElement.addAttribute("userUuid", categoryProperty.getUserUuid());
      propertyElement.addAttribute("key", categoryProperty.getKey());
      propertyElement.addAttribute("value", categoryProperty.getValue());
    }

    String categoryPath = ExportImportPathUtil.getModelPath(category);

    categoryElement.addAttribute("path", categoryPath);

    portletDataContext.addPermissions(AssetCategory.class, category.getCategoryId());

    portletDataContext.addZipEntry(categoryPath, category);
  }
  protected JSONArray toJSONArray(List<AssetCategory> categories)
      throws PortalException, SystemException {

    JSONArray jsonArray = JSONFactoryUtil.createJSONArray();

    for (AssetCategory category : categories) {
      String categoryJSON = JSONFactoryUtil.looseSerialize(category);

      JSONObject categoryJSONObject = JSONFactoryUtil.createJSONObject(categoryJSON);

      List<String> names = new ArrayList<String>();

      AssetCategory curCategory = category;

      while (curCategory.getParentCategoryId() > 0) {
        AssetCategory parentCategory = getCategory(curCategory.getParentCategoryId());

        names.add(parentCategory.getName());
        names.add(StringPool.SPACE + StringPool.GREATER_THAN + StringPool.SPACE);

        curCategory = parentCategory;
      }

      Collections.reverse(names);

      AssetVocabulary vocabulary = assetVocabularyService.getVocabulary(category.getVocabularyId());

      StringBundler sb = new StringBundler(1 + names.size());

      sb.append(vocabulary.getName());
      sb.append(names.toArray(new String[names.size()]));

      categoryJSONObject.put("path", sb.toString());

      jsonArray.put(categoryJSONObject);
    }

    return jsonArray;
  }
Ejemplo n.º 20
0
  public static void addPortletBreadcrumbEntries(
      long assetCategoryId, HttpServletRequest request, PortletURL portletURL) throws Exception {

    AssetCategory assetCategory = AssetCategoryLocalServiceUtil.getCategory(assetCategoryId);

    List<AssetCategory> ancestorCategories = assetCategory.getAncestors();

    Collections.reverse(ancestorCategories);

    for (AssetCategory ancestorCategory : ancestorCategories) {
      portletURL.setParameter("categoryId", String.valueOf(ancestorCategory.getCategoryId()));

      PortalUtil.addPortletBreadcrumbEntry(
          request, ancestorCategory.getTitleCurrentValue(), portletURL.toString());
    }

    portletURL.setParameter("categoryId", String.valueOf(assetCategoryId));

    PortalUtil.addPortletBreadcrumbEntry(
        request, assetCategory.getTitleCurrentValue(), portletURL.toString());
  }
  @Override
  protected Document doGetDocument(Object obj) throws Exception {
    AssetCategory category = (AssetCategory) obj;

    if (_log.isDebugEnabled()) {
      _log.debug("Indexing category " + category);
    }

    Document document = getBaseModelDocument(PORTLET_ID, category);

    document.addKeyword(Field.ASSET_CATEGORY_ID, category.getCategoryId());
    document.addKeyword(Field.ASSET_VOCABULARY_ID, category.getVocabularyId());
    document.addLocalizedText(Field.DESCRIPTION, category.getDescriptionMap());
    document.addText(Field.NAME, category.getName());
    document.addLocalizedText(Field.TITLE, category.getTitleMap());

    if (_log.isDebugEnabled()) {
      _log.debug("Document " + category + " indexed successfully");
    }

    return document;
  }
  @Indexable(type = IndexableType.REINDEX)
  @Override
  public AssetCategory addCategory(
      long userId,
      long parentCategoryId,
      Map<Locale, String> titleMap,
      Map<Locale, String> descriptionMap,
      long vocabularyId,
      String[] categoryProperties,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    // Category

    User user = userPersistence.findByPrimaryKey(userId);
    long groupId = serviceContext.getScopeGroupId();

    String name = titleMap.get(LocaleUtil.getSiteDefault());

    name = ModelHintsUtil.trimString(AssetCategory.class.getName(), "name", name);

    if (categoryProperties == null) {
      categoryProperties = new String[0];
    }

    Date now = new Date();

    validate(0, parentCategoryId, name, vocabularyId);

    if (parentCategoryId > 0) {
      assetCategoryPersistence.findByPrimaryKey(parentCategoryId);
    }

    assetVocabularyPersistence.findByPrimaryKey(vocabularyId);

    long categoryId = counterLocalService.increment();

    AssetCategory category = assetCategoryPersistence.create(categoryId);

    category.setUuid(serviceContext.getUuid());
    category.setGroupId(groupId);
    category.setCompanyId(user.getCompanyId());
    category.setUserId(user.getUserId());
    category.setUserName(user.getFullName());
    category.setCreateDate(now);
    category.setModifiedDate(now);
    category.setParentCategoryId(parentCategoryId);
    category.setName(name);
    category.setTitleMap(titleMap);
    category.setDescriptionMap(descriptionMap);
    category.setVocabularyId(vocabularyId);

    assetCategoryPersistence.update(category);

    // Resources

    if (serviceContext.isAddGroupPermissions() || serviceContext.isAddGuestPermissions()) {

      addCategoryResources(
          category, serviceContext.isAddGroupPermissions(), serviceContext.isAddGuestPermissions());
    } else {
      addCategoryResources(
          category, serviceContext.getGroupPermissions(), serviceContext.getGuestPermissions());
    }

    // Properties

    for (int i = 0; i < categoryProperties.length; i++) {
      String[] categoryProperty =
          StringUtil.split(
              categoryProperties[i], AssetCategoryConstants.PROPERTY_KEY_VALUE_SEPARATOR);

      if (categoryProperty.length <= 1) {
        categoryProperty = StringUtil.split(categoryProperties[i], CharPool.COLON);
      }

      String key = StringPool.BLANK;
      String value = StringPool.BLANK;

      if (categoryProperty.length > 1) {
        key = GetterUtil.getString(categoryProperty[0]);
        value = GetterUtil.getString(categoryProperty[1]);
      }

      if (Validator.isNotNull(key)) {
        assetCategoryPropertyLocalService.addCategoryProperty(userId, categoryId, key, value);
      }
    }

    return category;
  }
Ejemplo n.º 23
0
  protected void readAssetCategories(PortletDataContext portletDataContext) throws Exception {

    String xml =
        portletDataContext.getZipEntryAsString(
            portletDataContext.getSourceRootPath() + "/categories-hierarchy.xml");

    if (xml == null) {
      return;
    }

    Document document = SAXReaderUtil.read(xml);

    Element rootElement = document.getRootElement();

    Element assetVocabulariesElement = rootElement.element("vocabularies");

    List<Element> assetVocabularyElements = assetVocabulariesElement.elements("vocabulary");

    Map<Long, Long> assetVocabularyPKs =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(AssetVocabulary.class);

    for (Element assetVocabularyElement : assetVocabularyElements) {
      String path = assetVocabularyElement.attributeValue("path");

      if (!portletDataContext.isPathNotProcessed(path)) {
        continue;
      }

      AssetVocabulary assetVocabulary =
          (AssetVocabulary) portletDataContext.getZipEntryAsObject(path);

      importAssetVocabulary(
          portletDataContext, assetVocabularyPKs, assetVocabularyElement, assetVocabulary);
    }

    Element assetCategoriesElement = rootElement.element("categories");

    List<Element> assetCategoryElements = assetCategoriesElement.elements("category");

    Map<Long, Long> assetCategoryPKs =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(AssetCategory.class);

    Map<String, String> assetCategoryUuids =
        (Map<String, String>)
            portletDataContext.getNewPrimaryKeysMap(AssetCategory.class.getName() + "uuid");

    for (Element assetCategoryElement : assetCategoryElements) {
      String path = assetCategoryElement.attributeValue("path");

      if (!portletDataContext.isPathNotProcessed(path)) {
        continue;
      }

      AssetCategory assetCategory = (AssetCategory) portletDataContext.getZipEntryAsObject(path);

      importAssetCategory(
          portletDataContext,
          assetVocabularyPKs,
          assetCategoryPKs,
          assetCategoryUuids,
          assetCategoryElement,
          assetCategory);
    }

    Element assetsElement = rootElement.element("assets");

    List<Element> assetElements = assetsElement.elements("asset");

    for (Element assetElement : assetElements) {
      String className = GetterUtil.getString(assetElement.attributeValue("class-name"));
      long classPK = GetterUtil.getLong(assetElement.attributeValue("class-pk"));
      String[] assetCategoryUuidArray =
          StringUtil.split(GetterUtil.getString(assetElement.attributeValue("category-uuids")));

      long[] assetCategoryIds = new long[0];

      for (String assetCategoryUuid : assetCategoryUuidArray) {
        assetCategoryUuid =
            MapUtil.getString(assetCategoryUuids, assetCategoryUuid, assetCategoryUuid);

        AssetCategory assetCategory =
            AssetCategoryUtil.fetchByUUID_G(
                assetCategoryUuid, portletDataContext.getScopeGroupId());

        if (assetCategory == null) {
          Group companyGroup =
              GroupLocalServiceUtil.getCompanyGroup(portletDataContext.getCompanyId());

          assetCategory =
              AssetCategoryUtil.fetchByUUID_G(assetCategoryUuid, companyGroup.getGroupId());
        }

        if (assetCategory != null) {
          assetCategoryIds = ArrayUtil.append(assetCategoryIds, assetCategory.getCategoryId());
        }
      }

      portletDataContext.addAssetCategories(className, classPK, assetCategoryIds);
    }
  }
Ejemplo n.º 24
0
  protected void importAssetCategory(
      PortletDataContext portletDataContext,
      Map<Long, Long> assetVocabularyPKs,
      Map<Long, Long> assetCategoryPKs,
      Map<String, String> assetCategoryUuids,
      Element assetCategoryElement,
      AssetCategory assetCategory)
      throws Exception {

    long userId = portletDataContext.getUserId(assetCategory.getUserUuid());
    long assetVocabularyId =
        MapUtil.getLong(
            assetVocabularyPKs, assetCategory.getVocabularyId(), assetCategory.getVocabularyId());
    long parentAssetCategoryId =
        MapUtil.getLong(
            assetCategoryPKs,
            assetCategory.getParentCategoryId(),
            assetCategory.getParentCategoryId());

    if ((parentAssetCategoryId != AssetCategoryConstants.DEFAULT_PARENT_CATEGORY_ID)
        && (parentAssetCategoryId == assetCategory.getParentCategoryId())) {

      String path = getAssetCategoryPath(portletDataContext, parentAssetCategoryId);

      AssetCategory parentAssetCategory =
          (AssetCategory) portletDataContext.getZipEntryAsObject(path);

      Node parentCategoryNode =
          assetCategoryElement.getParent().selectSingleNode("./category[@path='" + path + "']");

      if (parentCategoryNode != null) {
        importAssetCategory(
            portletDataContext,
            assetVocabularyPKs,
            assetCategoryPKs,
            assetCategoryUuids,
            (Element) parentCategoryNode,
            parentAssetCategory);

        parentAssetCategoryId =
            MapUtil.getLong(
                assetCategoryPKs,
                assetCategory.getParentCategoryId(),
                assetCategory.getParentCategoryId());
      }
    }

    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setAddGroupPermissions(true);
    serviceContext.setAddGuestPermissions(true);
    serviceContext.setCreateDate(assetCategory.getCreateDate());
    serviceContext.setModifiedDate(assetCategory.getModifiedDate());
    serviceContext.setScopeGroupId(portletDataContext.getScopeGroupId());

    AssetCategory importedAssetCategory = null;

    try {
      if (parentAssetCategoryId != AssetCategoryConstants.DEFAULT_PARENT_CATEGORY_ID) {

        AssetCategoryUtil.findByPrimaryKey(parentAssetCategoryId);
      }

      List<Element> propertyElements = assetCategoryElement.elements("property");

      String[] properties = new String[propertyElements.size()];

      for (int i = 0; i < propertyElements.size(); i++) {
        Element propertyElement = propertyElements.get(i);

        String key = propertyElement.attributeValue("key");
        String value = propertyElement.attributeValue("value");

        properties[i] = key.concat(StringPool.COLON).concat(value);
      }

      AssetCategory existingAssetCategory =
          AssetCategoryUtil.fetchByP_N_V(
              parentAssetCategoryId, assetCategory.getName(), assetVocabularyId);

      if (existingAssetCategory == null) {
        serviceContext.setUuid(assetCategory.getUuid());

        importedAssetCategory =
            AssetCategoryLocalServiceUtil.addCategory(
                userId,
                parentAssetCategoryId,
                getAssetCategoryTitleMap(assetCategory),
                assetCategory.getDescriptionMap(),
                assetVocabularyId,
                properties,
                serviceContext);
      } else {
        importedAssetCategory =
            AssetCategoryLocalServiceUtil.updateCategory(
                userId,
                existingAssetCategory.getCategoryId(),
                parentAssetCategoryId,
                getAssetCategoryTitleMap(assetCategory),
                assetCategory.getDescriptionMap(),
                assetVocabularyId,
                properties,
                serviceContext);
      }

      assetCategoryPKs.put(assetCategory.getCategoryId(), importedAssetCategory.getCategoryId());

      assetCategoryUuids.put(assetCategory.getUuid(), importedAssetCategory.getUuid());

      portletDataContext.importPermissions(
          AssetCategory.class,
          assetCategory.getCategoryId(),
          importedAssetCategory.getCategoryId());
    } catch (NoSuchCategoryException nsce) {
      _log.error(
          "Could not find the parent category for category " + assetCategory.getCategoryId());
    }
  }
  protected void importAssets(CalEvent calEvent, long calendarBookingId)
      throws PortalException, SystemException {

    // Asset entry

    AssetEntry assetEntry =
        assetEntryPersistence.fetchByC_C(
            classNameLocalService.getClassNameId(CalEvent.class.getName()), calEvent.getEventId());

    if (assetEntry == null) {
      return;
    }

    long entryId = counterLocalService.increment();

    addAssetEntry(
        entryId,
        assetEntry.getGroupId(),
        assetEntry.getCompanyId(),
        assetEntry.getUserId(),
        assetEntry.getUserName(),
        assetEntry.getCreateDate(),
        assetEntry.getModifiedDate(),
        classNameLocalService.getClassNameId(CalendarBooking.class.getName()),
        calendarBookingId,
        calEvent.getUuid(),
        assetEntry.isVisible(),
        assetEntry.getStartDate(),
        assetEntry.getEndDate(),
        assetEntry.getPublishDate(),
        assetEntry.getExpirationDate(),
        assetEntry.getMimeType(),
        assetEntry.getTitle(),
        assetEntry.getDescription(),
        assetEntry.getSummary(),
        assetEntry.getUrl(),
        assetEntry.getLayoutUuid(),
        assetEntry.getHeight(),
        assetEntry.getWidth(),
        assetEntry.getPriority(),
        assetEntry.getViewCount());

    // Asset categories

    List<AssetCategory> assetCategories = new ArrayList<AssetCategory>();

    assetCategories.addAll(assetEntry.getCategories());

    assetCategories.add(
        getAssetCategory(calEvent.getUserId(), calEvent.getGroupId(), calEvent.getType()));

    for (AssetCategory assetCategory : assetCategories) {
      assetEntryLocalService.addAssetCategoryAssetEntry(assetCategory.getCategoryId(), entryId);
    }

    // Asset links

    List<AssetLink> assetLinks = assetLinkLocalService.getDirectLinks(assetEntry.getEntryId());

    for (AssetLink assetLink : assetLinks) {
      importAssetLink(assetLink, entryId);
    }

    // Asset tags

    List<AssetTag> assetTags = assetEntry.getTags();

    for (AssetTag assetTag : assetTags) {
      assetEntryLocalService.addAssetTagAssetEntry(assetTag.getTagId(), entryId);
    }
  }
Ejemplo n.º 26
0
  public static PortletURL getAddPortletURL(
      LiferayPortletRequest liferayPortletRequest,
      LiferayPortletResponse liferayPortletResponse,
      long groupId,
      String className,
      long classTypeId,
      long[] allAssetCategoryIds,
      String[] allAssetTagNames,
      String redirect)
      throws Exception {

    ThemeDisplay themeDisplay =
        (ThemeDisplay) liferayPortletRequest.getAttribute(WebKeys.THEME_DISPLAY);

    AssetRendererFactory<?> assetRendererFactory =
        AssetRendererFactoryRegistryUtil.getAssetRendererFactoryByClassName(className);

    if ((assetRendererFactory == null)
        || !assetRendererFactory.hasAddPermission(
            themeDisplay.getPermissionChecker(), groupId, classTypeId)) {

      return null;
    }

    PortletURL addPortletURL =
        assetRendererFactory.getURLAdd(liferayPortletRequest, liferayPortletResponse, classTypeId);

    if (addPortletURL == null) {
      return null;
    }

    if (redirect != null) {
      addPortletURL.setParameter("redirect", redirect);
    }

    String referringPortletResource = ParamUtil.getString(liferayPortletRequest, "portletResource");

    if (Validator.isNotNull(referringPortletResource)) {
      addPortletURL.setParameter("referringPortletResource", referringPortletResource);
    } else {
      PortletDisplay portletDisplay = themeDisplay.getPortletDisplay();

      addPortletURL.setParameter("referringPortletResource", portletDisplay.getId());

      if (allAssetCategoryIds != null) {
        Map<Long, String> assetVocabularyAssetCategoryIds = new HashMap<>();

        for (long assetCategoryId : allAssetCategoryIds) {
          AssetCategory assetCategory =
              AssetCategoryLocalServiceUtil.fetchAssetCategory(assetCategoryId);

          if (assetCategory == null) {
            continue;
          }

          long assetVocabularyId = assetCategory.getVocabularyId();

          if (assetVocabularyAssetCategoryIds.containsKey(assetVocabularyId)) {

            String assetCategoryIds = assetVocabularyAssetCategoryIds.get(assetVocabularyId);

            assetVocabularyAssetCategoryIds.put(
                assetVocabularyId, assetCategoryIds + StringPool.COMMA + assetCategoryId);
          } else {
            assetVocabularyAssetCategoryIds.put(assetVocabularyId, String.valueOf(assetCategoryId));
          }
        }

        for (Map.Entry<Long, String> entry : assetVocabularyAssetCategoryIds.entrySet()) {

          long assetVocabularyId = entry.getKey();
          String assetCategoryIds = entry.getValue();

          addPortletURL.setParameter("assetCategoryIds_" + assetVocabularyId, assetCategoryIds);
        }
      }

      if (allAssetTagNames != null) {
        addPortletURL.setParameter("assetTagNames", StringUtil.merge(allAssetTagNames));
      }
    }

    addPortletURL.setPortletMode(PortletMode.VIEW);
    addPortletURL.setWindowState(LiferayWindowState.POP_UP);

    return addPortletURL;
  }
  public void loadCategoriesFromCsv(ActionRequest actionRequest, ActionResponse actionResponse)
      throws IOException, PortletException, PortalException, SystemException {

    LOGGER.info("Begin  AssetCategoriesImporter");
    UploadPortletRequest uploadPortletRequest = PortalUtil.getUploadPortletRequest(actionRequest);
    ThemeDisplay themeDisplay =
        (ThemeDisplay) uploadPortletRequest.getAttribute(WebKeys.THEME_DISPLAY);
    Map<String, FileItem[]> multipartParameterMap = uploadPortletRequest.getMultipartParameterMap();

    File file = null;
    BufferedReader bufferedReader = null;
    AssetVocabulary assetVocabulary = null;
    long userId = themeDisplay.getUserId();
    long groupId = themeDisplay.getScopeGroupId();

    ServiceContext serviceContext =
        ServiceContextFactory.getInstance(AssetCategory.class.getName(), uploadPortletRequest);

    // create vocabulary
    try {

      assetVocabulary =
          AssetVocabularyLocalServiceUtil.addVocabulary(
              userId,
              "Announcements",
              ServiceContextFactory.getInstance(
                  AssetVocabulary.class.getName(), uploadPortletRequest));
    } catch (DuplicateVocabularyException dve) {
      try {
        assetVocabulary =
            AssetVocabularyLocalServiceUtil.getGroupVocabulary(groupId, "Announcements");
      } catch (PortalException e) {
        if (LOGGER.isDebugEnabled()) {
          LOGGER.debug(e);
        }
        LOGGER.error(e.getMessage());
      } catch (SystemException e) {
        if (LOGGER.isDebugEnabled()) {
          LOGGER.debug(e);
        }
        LOGGER.error(e.getMessage());
      }
    }

    if (multipartParameterMap.keySet().contains("fileCategory")
        && Validator.isNotNull(assetVocabulary)) {
      try {
        file = uploadPortletRequest.getFile("fileCategory");
        bufferedReader = new BufferedReader(new FileReader(file.getAbsolutePath()));
        String line = StringPool.BLANK;
        long vocabularyId = assetVocabulary.getVocabularyId();

        String parentCategoryName = StringPool.BLANK;
        AssetCategory parentCategory = null;

        while ((line = bufferedReader.readLine()) != null) {

          // use comma as separator
          String[] categories = line.split(StringPool.SEMICOLON);

          if (categories.length == 4) {
            String parentCategoryCode = categories[0];

            if (Validator.isNull(parentCategory) || !parentCategoryName.equals(categories[1])) {
              parentCategoryName = categories[1];
              try {
                parentCategory =
                    AssetCategoryLocalServiceUtil.addCategory(
                        userId, parentCategoryName, vocabularyId, serviceContext);
                AssetCategoryPropertyLocalServiceUtil.addCategoryProperty(
                    userId, parentCategory.getCategoryId(), "Code", parentCategoryCode);
              } catch (Exception e) {
                if (LOGGER.isDebugEnabled()) {
                  LOGGER.debug(e);
                }
                LOGGER.error(e.getMessage());
              }
            }

            Map<Locale, String> titles = new HashMap<Locale, String>();
            Map<Locale, String> descriptionMap = new HashMap<Locale, String>();

            titles.put(LocaleUtil.fromLanguageId("fr_FR"), categories[3]);
            titles.put(LocaleUtil.fromLanguageId("en_US"), categories[3]);

            try {
              AssetCategory child =
                  AssetCategoryLocalServiceUtil.addCategory(
                      userId,
                      parentCategory.getCategoryId(),
                      titles,
                      descriptionMap,
                      vocabularyId,
                      null,
                      serviceContext);
              AssetCategoryPropertyLocalServiceUtil.addCategoryProperty(
                  userId, child.getCategoryId(), "Code", categories[2]);
            } catch (Exception e) {
              if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(e);
              }
              LOGGER.error(e.getMessage());
            }
          }
        }
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        if (bufferedReader != null) {
          try {
            bufferedReader.close();
          } catch (IOException e) {
            if (LOGGER.isDebugEnabled()) {
              LOGGER.debug(e);
            }
            LOGGER.error(e.getMessage());
          }
        }
      }
    }
    LOGGER.info("End  AssetCategoriesImporter");
  }
  @Override
  protected void doImportStagedModel(PortletDataContext portletDataContext, AssetCategory category)
      throws Exception {

    long userId = portletDataContext.getUserId(category.getUserUuid());

    if (category.getParentCategoryId() != AssetCategoryConstants.DEFAULT_PARENT_CATEGORY_ID) {

      StagedModelDataHandlerUtil.importReferenceStagedModel(
          portletDataContext, category, AssetCategory.class, category.getParentCategoryId());
    } else {
      StagedModelDataHandlerUtil.importReferenceStagedModel(
          portletDataContext, category, AssetVocabulary.class, category.getVocabularyId());
    }

    Map<Long, Long> vocabularyIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(AssetVocabulary.class);

    long vocabularyId =
        MapUtil.getLong(vocabularyIds, category.getVocabularyId(), category.getVocabularyId());

    Map<Long, Long> categoryIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(AssetCategory.class);

    long parentCategoryId =
        MapUtil.getLong(
            categoryIds, category.getParentCategoryId(), category.getParentCategoryId());

    Element categoryElement = portletDataContext.getImportDataElement(category);

    List<Element> propertyElements = categoryElement.elements("property");

    String[] properties = new String[propertyElements.size()];

    for (int i = 0; i < propertyElements.size(); i++) {
      Element propertyElement = propertyElements.get(i);

      String key = propertyElement.attributeValue("key");
      String value = propertyElement.attributeValue("value");

      properties[i] = key.concat(AssetCategoryConstants.PROPERTY_KEY_VALUE_SEPARATOR).concat(value);
    }

    ServiceContext serviceContext = createServiceContext(portletDataContext, category);

    AssetCategory importedCategory = null;

    AssetCategory existingCategory =
        AssetCategoryUtil.fetchByUUID_G(category.getUuid(), portletDataContext.getScopeGroupId());

    if (existingCategory == null) {
      existingCategory =
          AssetCategoryUtil.fetchByUUID_G(
              category.getUuid(), portletDataContext.getCompanyGroupId());
    }

    if (existingCategory == null) {
      String name =
          getCategoryName(
              null,
              portletDataContext.getScopeGroupId(),
              parentCategoryId,
              category.getName(),
              category.getVocabularyId(),
              2);

      serviceContext.setUuid(category.getUuid());

      importedCategory =
          AssetCategoryLocalServiceUtil.addCategory(
              userId,
              parentCategoryId,
              getCategoryTitleMap(portletDataContext.getScopeGroupId(), category, name),
              category.getDescriptionMap(),
              vocabularyId,
              properties,
              serviceContext);
    } else {
      String name =
          getCategoryName(
              category.getUuid(),
              portletDataContext.getScopeGroupId(),
              parentCategoryId,
              category.getName(),
              category.getVocabularyId(),
              2);

      importedCategory =
          AssetCategoryLocalServiceUtil.updateCategory(
              userId,
              existingCategory.getCategoryId(),
              parentCategoryId,
              getCategoryTitleMap(portletDataContext.getScopeGroupId(), category, name),
              category.getDescriptionMap(),
              vocabularyId,
              properties,
              serviceContext);
    }

    categoryIds.put(category.getCategoryId(), importedCategory.getCategoryId());

    Map<String, String> categoryUuids =
        (Map<String, String>)
            portletDataContext.getNewPrimaryKeysMap(AssetCategory.class + ".uuid");

    categoryUuids.put(category.getUuid(), importedCategory.getUuid());

    portletDataContext.importPermissions(
        AssetCategory.class, category.getCategoryId(), importedCategory.getCategoryId());
  }
  @Indexable(type = IndexableType.REINDEX)
  @Override
  public AssetCategory updateCategory(
      long userId,
      long categoryId,
      long parentCategoryId,
      Map<Locale, String> titleMap,
      Map<Locale, String> descriptionMap,
      long vocabularyId,
      String[] categoryProperties,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    // Category

    String name = titleMap.get(LocaleUtil.getSiteDefault());

    name = ModelHintsUtil.trimString(AssetCategory.class.getName(), "name", name);

    if (categoryProperties == null) {
      categoryProperties = new String[0];
    }

    validate(categoryId, parentCategoryId, name, vocabularyId);

    if (parentCategoryId > 0) {
      assetCategoryPersistence.findByPrimaryKey(parentCategoryId);
    }

    AssetCategory category = assetCategoryPersistence.findByPrimaryKey(categoryId);

    String oldName = category.getName();

    if (vocabularyId != category.getVocabularyId()) {
      assetVocabularyPersistence.findByPrimaryKey(vocabularyId);

      parentCategoryId = AssetCategoryConstants.DEFAULT_PARENT_CATEGORY_ID;

      category.setVocabularyId(vocabularyId);

      updateChildrenVocabularyId(category, vocabularyId);
    }

    category.setModifiedDate(new Date());
    category.setParentCategoryId(parentCategoryId);
    category.setName(name);
    category.setTitleMap(titleMap);
    category.setDescriptionMap(descriptionMap);

    assetCategoryPersistence.update(category);

    // Properties

    List<AssetCategoryProperty> oldCategoryProperties =
        assetCategoryPropertyPersistence.findByCategoryId(categoryId);

    oldCategoryProperties = ListUtil.copy(oldCategoryProperties);

    for (int i = 0; i < categoryProperties.length; i++) {
      String[] categoryProperty =
          StringUtil.split(
              categoryProperties[i], AssetCategoryConstants.PROPERTY_KEY_VALUE_SEPARATOR);

      if (categoryProperty.length <= 1) {
        categoryProperty = StringUtil.split(categoryProperties[i], CharPool.COLON);
      }

      String key = StringPool.BLANK;

      if (categoryProperty.length > 0) {
        key = GetterUtil.getString(categoryProperty[0]);
      }

      String value = StringPool.BLANK;

      if (categoryProperty.length > 1) {
        value = GetterUtil.getString(categoryProperty[1]);
      }

      if (Validator.isNotNull(key)) {
        boolean addCategoryProperty = true;

        AssetCategoryProperty oldCategoryProperty = null;

        Iterator<AssetCategoryProperty> iterator = oldCategoryProperties.iterator();

        while (iterator.hasNext()) {
          oldCategoryProperty = iterator.next();

          if ((categoryId == oldCategoryProperty.getCategoryId())
              && key.equals(oldCategoryProperty.getKey())) {

            addCategoryProperty = false;

            if (!value.equals(oldCategoryProperty.getValue())) {
              assetCategoryPropertyLocalService.updateCategoryProperty(
                  userId, oldCategoryProperty.getCategoryPropertyId(), key, value);
            }

            iterator.remove();

            break;
          }
        }

        if (addCategoryProperty) {
          assetCategoryPropertyLocalService.addCategoryProperty(userId, categoryId, key, value);
        }
      }
    }

    for (AssetCategoryProperty categoryProperty : oldCategoryProperties) {
      assetCategoryPropertyLocalService.deleteAssetCategoryProperty(categoryProperty);
    }

    // Indexer

    if (!oldName.equals(name)) {
      List<AssetEntry> entries = assetCategoryPersistence.getAssetEntries(category.getCategoryId());

      assetEntryLocalService.reindex(entries);
    }

    return category;
  }
 @Override
 public String getDisplayName(AssetCategory category) {
   return category.getTitleCurrentValue();
 }