@Before
  public void setUp() throws Exception {
    ServiceTestUtil.setUser(TestPropsValues.getUser());

    ServiceContext serviceContext = ServiceContextTestUtil.getServiceContext();

    _repository =
        RepositoryLocalServiceUtil.addRepository(
            TestPropsValues.getUserId(),
            TestPropsValues.getGroupId(),
            ClassNameLocalServiceUtil.getClassNameId(_REPOSITORY_CLASS_NAME),
            DLFolderConstants.DEFAULT_PARENT_FOLDER_ID,
            StringUtil.randomString(),
            StringUtil.randomString(),
            StringUtil.randomString(),
            new UnicodeProperties(),
            true,
            serviceContext);

    _repositoryEntry =
        RepositoryEntryLocalServiceUtil.createRepositoryEntry(_repository.getDlFolderId());

    _repositoryEntry.setUuid(serviceContext.getUuid());
    _repositoryEntry.setGroupId(serviceContext.getScopeGroupId());
    _repositoryEntry.setCompanyId(serviceContext.getCompanyId());
    _repositoryEntry.setUserId(serviceContext.getUserId());
    _repositoryEntry.setUserName(StringUtil.randomString());
    _repositoryEntry.setCreateDate(serviceContext.getCreateDate(null));
    _repositoryEntry.setModifiedDate(serviceContext.getModifiedDate(null));
    _repositoryEntry.setRepositoryId(_repository.getRepositoryId());
    _repositoryEntry.setMappedId(_MAPPED_ID);

    RepositoryEntryLocalServiceUtil.addRepositoryEntry(_repositoryEntry);
  }
  @Test
  public void testUserGroupMemberRule() throws Exception {
    ServiceContext serviceContext = ServiceTestUtil.getServiceContext();

    AnonymousUser anonymousUser =
        _anonymousUserLocalService.addAnonymousUser(
            TestPropsValues.getUserId(), "127.0.0.1", StringPool.BLANK, serviceContext);

    Rule rule = _rulesRegistry.getRule("UserGroupMemberRule");

    UserGroup userGroup =
        UserGroupLocalServiceUtil.addUserGroup(
            TestPropsValues.getUserId(),
            TestPropsValues.getCompanyId(),
            StringUtil.randomString(),
            StringUtil.randomString(),
            new ServiceContext());

    UserGroupLocalServiceUtil.addUserUserGroup(
        TestPropsValues.getUserId(), userGroup.getUserGroupId());

    RuleInstance ruleInstance =
        _ruleInstanceLocalService.addRuleInstance(
            TestPropsValues.getUserId(),
            rule.getRuleKey(),
            0,
            String.valueOf(userGroup.getUserGroupId()),
            serviceContext);

    Assert.assertTrue(rule.evaluate(null, ruleInstance, anonymousUser));
  }
Esempio n. 3
0
  protected void addDDMFormFieldOptions(
      JSONObject jsonObject,
      DDMFormField ddmFormField,
      Set<Locale> availableLocales,
      Locale defaultLocale) {

    String type = ddmFormField.getType();

    if (!(type.equals(DDMImpl.TYPE_RADIO) || type.equals(DDMImpl.TYPE_SELECT))) {

      return;
    }

    String fieldName = ddmFormField.getName();

    JSONArray jsonArray = JSONFactoryUtil.createJSONArray();

    DDMFormFieldOptions ddmFormFieldOptions = ddmFormField.getDDMFormFieldOptions();

    for (String optionValue : ddmFormFieldOptions.getOptionsValues()) {
      JSONObject optionJSONObject = JSONFactoryUtil.createJSONObject();

      String name = fieldName.concat(StringUtil.randomString());

      optionJSONObject.put("id", name);
      optionJSONObject.put("name", name);
      optionJSONObject.put("type", "option");
      optionJSONObject.put("value", optionValue);

      addDDMFormFieldLocalizedProperty(
          optionJSONObject,
          "label",
          ddmFormFieldOptions.getOptionLabels(optionValue),
          defaultLocale,
          defaultLocale,
          "option");

      JSONObject localizationMapJSONObject = JSONFactoryUtil.createJSONObject();

      for (Locale availableLocale : availableLocales) {
        JSONObject localeMap = JSONFactoryUtil.createJSONObject();

        addDDMFormFieldLocalizedProperty(
            localeMap,
            "label",
            ddmFormFieldOptions.getOptionLabels(optionValue),
            availableLocale,
            defaultLocale,
            "option");

        localizationMapJSONObject.put(LocaleUtil.toLanguageId(availableLocale), localeMap);
      }

      optionJSONObject.put("localizationMap", localizationMapJSONObject);

      jsonArray.put(optionJSONObject);
    }

    jsonObject.put("options", jsonArray);
  }
  @Test
  public void testOrganizationMemberRule() throws Exception {
    ServiceContext serviceContext = ServiceTestUtil.getServiceContext();

    AnonymousUser anonymousUser =
        _anonymousUserLocalService.addAnonymousUser(
            TestPropsValues.getUserId(), "127.0.0.1", StringPool.BLANK, serviceContext);

    Rule rule = _rulesRegistry.getRule("OrganizationMemberRule");

    Organization organization =
        OrganizationLocalServiceUtil.addOrganization(
            TestPropsValues.getUserId(),
            OrganizationConstants.DEFAULT_PARENT_ORGANIZATION_ID,
            StringUtil.randomString(),
            false);

    OrganizationLocalServiceUtil.addUserOrganization(
        TestPropsValues.getUserId(), organization.getOrganizationId());

    RuleInstance ruleInstance =
        _ruleInstanceLocalService.addRuleInstance(
            TestPropsValues.getUserId(),
            rule.getRuleKey(),
            0,
            String.valueOf(organization.getOrganizationId()),
            serviceContext);

    Assert.assertTrue(rule.evaluate(null, ruleInstance, anonymousUser));
  }
  @BeforeClass
  public static void setUpClass() {
    _CLASS_NAME_ID = PortalUtil.getClassNameId(StringUtil.randomString());

    _enLocale = LocaleUtil.fromLanguageId("en_US");
    _ptLocale = LocaleUtil.fromLanguageId("pt_BR");

    _jsonStorageAdapter = StorageAdapterRegistryUtil.getStorageAdapter(StorageType.JSON.toString());
  }
  protected String getPortletJavaScript(Bundle bundle, String path) throws Exception {

    SoyPortletHelper soyPortletHelper = new SoyPortletHelper(bundle);

    Template template = new MockTemplate();

    String portletJavaScript =
        soyPortletHelper.getPortletJavaScript(
            template, path, StringUtil.randomString(), Collections.<String>emptySet());

    return portletJavaScript;
  }
  @Test
  public void testEmailEntryUpdatedNotSentIfNotSpecified() throws Exception {
    BlogsEntry entry = BlogsTestUtil.addEntry(_group, true);

    BlogsEntryLocalServiceUtil.subscribe(_user.getUserId(), _group.getGroupId());

    ServiceContext serviceContext = ServiceContextTestUtil.getServiceContext(entry.getGroupId());

    serviceContext.setAttribute("emailEntryUpdatedComment", "This entry was updated.");

    BlogsTestUtil.updateEntry(entry, StringUtil.randomString(), true, serviceContext);

    Assert.assertEquals(0, MailServiceTestUtil.getInboxSize());
  }
  protected String createDefaultDDMFormFieldParameterName(
      DDMFormField ddmFormField, String parentDefaultDDMFormFieldParameterName) {

    StringBundler sb = new StringBundler(7);

    if (Validator.isNotNull(parentDefaultDDMFormFieldParameterName)) {
      sb.append(parentDefaultDDMFormFieldParameterName);
      sb.append(DDMFormRendererConstants.DDM_FORM_FIELDS_SEPARATOR);
    }

    sb.append(ddmFormField.getName());
    sb.append(DDMFormRendererConstants.DDM_FORM_FIELD_PARTS_SEPARATOR);
    sb.append(StringUtil.randomString());
    sb.append(DDMFormRendererConstants.DDM_FORM_FIELD_PARTS_SEPARATOR);
    sb.append(0);

    return sb.toString();
  }
  @Test
  public void testEmailEntryUpdatedSentWithEmptyEmailEntryUpdatedComment() throws Exception {

    setUpBlogsSettings();

    BlogsEntry entry = BlogsTestUtil.addEntry(_group, true);

    BlogsEntryLocalServiceUtil.subscribe(_user.getUserId(), _group.getGroupId());

    ServiceContext serviceContext = ServiceContextTestUtil.getServiceContext(entry.getGroupId());

    serviceContext.setAttribute("sendEmailEntryUpdated", Boolean.TRUE.toString());

    BlogsTestUtil.updateEntry(entry, StringUtil.randomString(), true, serviceContext);

    MailMessage message = MailServiceTestUtil.getLastMailMessage();

    Assert.assertEquals(message.getBody(), StringPool.NEW_LINE);
  }
  protected void addTempFileEntry(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

    UploadPortletRequest uploadPortletRequest = PortalUtil.getUploadPortletRequest(actionRequest);

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

    long folderId = ParamUtil.getLong(uploadPortletRequest, "folderId");
    String sourceFileName = uploadPortletRequest.getFileName("file");

    StringBundler sb = new StringBundler(5);

    sb.append(FileUtil.stripExtension(sourceFileName));
    sb.append(DL.TEMP_RANDOM_SUFFIX);
    sb.append(StringUtil.randomString());

    String extension = FileUtil.getExtension(sourceFileName);

    if (Validator.isNotNull(extension)) {
      sb.append(StringPool.PERIOD);
      sb.append(extension);
    }

    InputStream inputStream = null;

    try {
      inputStream = uploadPortletRequest.getFileAsStream("file");

      String contentType = uploadPortletRequest.getContentType("file");

      FileEntry fileEntry =
          _dlAppService.addTempFileEntry(
              themeDisplay.getScopeGroupId(),
              folderId,
              TEMP_FOLDER_NAME,
              sb.toString(),
              inputStream,
              contentType);

      JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

      jsonObject.put("groupId", fileEntry.getGroupId());
      jsonObject.put("name", fileEntry.getTitle());
      jsonObject.put("title", sourceFileName);
      jsonObject.put("uuid", fileEntry.getUuid());

      JSONPortletResponseUtil.writeJSON(actionRequest, actionResponse, jsonObject);
    } catch (Exception e) {
      UploadException uploadException =
          (UploadException) actionRequest.getAttribute(WebKeys.UPLOAD_EXCEPTION);

      if ((uploadException != null)
          && (uploadException.getCause() instanceof FileUploadBase.IOFileUploadException)) {

        // Cancelled a temporary upload

      } else if ((uploadException != null) && uploadException.isExceededSizeLimit()) {

        throw new FileSizeException(uploadException.getCause());
      } else {
        throw e;
      }
    } finally {
      StreamUtil.cleanUp(inputStream);
    }
  }
  @Override
  protected void doImportStagedModel(PortletDataContext portletDataContext, FileEntry fileEntry)
      throws Exception {

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

    if (!fileEntry.isDefaultRepository()) {

      // References has been automatically imported, nothing to do here

      return;
    }

    Map<Long, Long> folderIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(Folder.class);

    long folderId = MapUtil.getLong(folderIds, fileEntry.getFolderId(), fileEntry.getFolderId());

    long[] assetCategoryIds =
        portletDataContext.getAssetCategoryIds(DLFileEntry.class, fileEntry.getFileEntryId());
    String[] assetTagNames =
        portletDataContext.getAssetTagNames(DLFileEntry.class, fileEntry.getFileEntryId());

    ServiceContext serviceContext =
        portletDataContext.createServiceContext(fileEntry, DLFileEntry.class);

    serviceContext.setAttribute("sourceFileName", "A." + fileEntry.getExtension());
    serviceContext.setUserId(userId);

    Element fileEntryElement = portletDataContext.getImportDataElement(fileEntry);

    String binPath = fileEntryElement.attributeValue("bin-path");

    InputStream is = null;

    if (Validator.isNull(binPath) && portletDataContext.isPerformDirectBinaryImport()) {

      try {
        is = FileEntryUtil.getContentStream(fileEntry);
      } catch (Exception e) {
        if (_log.isWarnEnabled()) {
          _log.warn("Unable to retrieve content for file entry " + fileEntry.getFileEntryId(), e);
        }

        return;
      }
    } else {
      is = portletDataContext.getZipEntryAsInputStream(binPath);
    }

    if (is == null) {
      if (_log.isWarnEnabled()) {
        _log.warn("No file found for file entry " + fileEntry.getFileEntryId());
      }

      return;
    }

    importMetaData(portletDataContext, fileEntryElement, fileEntry, serviceContext);

    FileEntry importedFileEntry = null;

    String titleWithExtension = DLUtil.getTitleWithExtension(fileEntry);
    String extension = fileEntry.getExtension();

    String periodAndExtension = StringPool.PERIOD.concat(extension);

    if (portletDataContext.isDataStrategyMirror()) {
      FileEntry existingFileEntry =
          fetchStagedModelByUuidAndGroupId(
              fileEntry.getUuid(), portletDataContext.getScopeGroupId());

      FileVersion fileVersion = fileEntry.getFileVersion();

      if (existingFileEntry == null) {
        String fileEntryTitle = fileEntry.getTitle();

        FileEntry existingTitleFileEntry =
            FileEntryUtil.fetchByR_F_T(
                portletDataContext.getScopeGroupId(), folderId, fileEntryTitle);

        if (existingTitleFileEntry != null) {
          if ((fileEntry.getGroupId() == portletDataContext.getSourceGroupId())
              && portletDataContext.isDataStrategyMirrorWithOverwriting()) {

            DLAppLocalServiceUtil.deleteFileEntry(existingTitleFileEntry.getFileEntryId());
          } else {
            boolean titleHasExtension = false;

            if (fileEntryTitle.endsWith(periodAndExtension)) {
              fileEntryTitle = FileUtil.stripExtension(fileEntryTitle);

              titleHasExtension = true;
            }

            for (int i = 1; ; i++) {
              fileEntryTitle += StringPool.SPACE + i;

              titleWithExtension = fileEntryTitle + periodAndExtension;

              existingTitleFileEntry =
                  FileEntryUtil.fetchByR_F_T(
                      portletDataContext.getScopeGroupId(), folderId, titleWithExtension);

              if (existingTitleFileEntry == null) {
                if (titleHasExtension) {
                  fileEntryTitle += periodAndExtension;
                }

                break;
              }
            }
          }
        }

        serviceContext.setAttribute("fileVersionUuid", fileVersion.getUuid());
        serviceContext.setUuid(fileEntry.getUuid());

        importedFileEntry =
            DLAppLocalServiceUtil.addFileEntry(
                userId,
                portletDataContext.getScopeGroupId(),
                folderId,
                titleWithExtension,
                fileEntry.getMimeType(),
                fileEntryTitle,
                fileEntry.getDescription(),
                null,
                is,
                fileEntry.getSize(),
                serviceContext);

        if (fileEntry.isInTrash()) {
          importedFileEntry =
              DLAppServiceUtil.moveFileEntryToTrash(importedFileEntry.getFileEntryId());
        }
      } else {
        FileVersion latestExistingFileVersion = existingFileEntry.getLatestFileVersion(true);

        boolean indexEnabled = serviceContext.isIndexingEnabled();

        boolean deleteFileEntry = false;
        boolean updateFileEntry = false;

        if (!Validator.equals(fileVersion.getUuid(), latestExistingFileVersion.getUuid())) {

          deleteFileEntry = true;
          updateFileEntry = true;
        } else {
          InputStream existingFileVersionInputStream = null;

          try {
            existingFileVersionInputStream = latestExistingFileVersion.getContentStream(false);
          } catch (Exception e) {
            if (_log.isDebugEnabled()) {
              _log.debug(e, e);
            }
          } finally {
            if (existingFileVersionInputStream != null) {
              existingFileVersionInputStream.close();
            }
          }

          if (existingFileVersionInputStream == null) {
            updateFileEntry = true;
          }
        }

        try {
          serviceContext.setIndexingEnabled(false);

          if (updateFileEntry) {
            DLFileVersion alreadyExistingFileVersion =
                DLFileVersionLocalServiceUtil.getFileVersionByUuidAndGroupId(
                    fileVersion.getUuid(), existingFileEntry.getGroupId());

            if (alreadyExistingFileVersion != null) {
              serviceContext.setAttribute(
                  "existingDLFileVersionId", alreadyExistingFileVersion.getFileVersionId());
            }

            serviceContext.setUuid(fileVersion.getUuid());

            importedFileEntry =
                DLAppLocalServiceUtil.updateFileEntry(
                    userId,
                    existingFileEntry.getFileEntryId(),
                    titleWithExtension,
                    fileEntry.getMimeType(),
                    fileEntry.getTitle(),
                    fileEntry.getDescription(),
                    null,
                    false,
                    is,
                    fileEntry.getSize(),
                    serviceContext);
          } else {
            DLAppLocalServiceUtil.updateAsset(
                userId, existingFileEntry,
                latestExistingFileVersion, assetCategoryIds,
                assetTagNames, null);

            importedFileEntry = existingFileEntry;
          }

          if (importedFileEntry.getFolderId() != folderId) {
            importedFileEntry =
                DLAppLocalServiceUtil.moveFileEntry(
                    userId, importedFileEntry.getFileEntryId(), folderId, serviceContext);
          }

          if (importedFileEntry instanceof LiferayFileEntry) {
            LiferayFileEntry liferayFileEntry = (LiferayFileEntry) importedFileEntry;

            Indexer<DLFileEntry> indexer =
                IndexerRegistryUtil.nullSafeGetIndexer(DLFileEntry.class);

            indexer.reindex((DLFileEntry) liferayFileEntry.getModel());
          }

          if (deleteFileEntry && ExportImportThreadLocal.isStagingInProcess()) {

            DLAppServiceUtil.deleteFileVersion(
                latestExistingFileVersion.getFileEntryId(), latestExistingFileVersion.getVersion());
          }
        } finally {
          serviceContext.setIndexingEnabled(indexEnabled);
        }
      }
    } else {
      try {
        importedFileEntry =
            DLAppLocalServiceUtil.addFileEntry(
                userId,
                portletDataContext.getScopeGroupId(),
                folderId,
                titleWithExtension,
                fileEntry.getMimeType(),
                fileEntry.getTitle(),
                fileEntry.getDescription(),
                null,
                is,
                fileEntry.getSize(),
                serviceContext);
      } catch (DuplicateFileException dfe) {
        String title = fileEntry.getTitle();

        String[] titleParts = title.split("\\.", 2);

        title = titleParts[0] + StringUtil.randomString();

        if (titleParts.length > 1) {
          title += StringPool.PERIOD + titleParts[1];
        }

        if (!title.endsWith(periodAndExtension)) {
          title += periodAndExtension;
        }

        importedFileEntry =
            DLAppLocalServiceUtil.addFileEntry(
                userId,
                portletDataContext.getScopeGroupId(),
                folderId,
                title,
                fileEntry.getMimeType(),
                title,
                fileEntry.getDescription(),
                null,
                is,
                fileEntry.getSize(),
                serviceContext);
      }
    }

    if (portletDataContext.getBooleanParameter(
        DLPortletDataHandler.NAMESPACE, "previews-and-thumbnails")) {

      DLProcessorRegistryUtil.importGeneratedFiles(
          portletDataContext, fileEntry, importedFileEntry, fileEntryElement);
    }

    portletDataContext.importClassedModel(fileEntry, importedFileEntry, DLFileEntry.class);

    Map<Long, Long> fileEntryIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(FileEntry.class);

    fileEntryIds.put(fileEntry.getFileEntryId(), importedFileEntry.getFileEntryId());
  }