public void processAction(ActionEvent actionEvent) throws AbortProcessingException {

      try {
        FolderUserObject folderUserObject = docLibModelBean.getSelectedFolderUserObject();
        DLFolder dlFolder = folderUserObject.getDlFolder();
        long groupId = dlFolder.getGroupId();
        long repositoryId = dlFolder.getRepositoryId();
        boolean mountPoint = dlFolder.getMountPoint();
        long parentFolderId = dlFolder.getFolderId();
        ServiceContext serviceContext = new ServiceContext();

        // Temporary: Make the default setting be that community members can view the file. Need to
        // develop a
        // "Viewable By" permissions Facelet composite component UI similar to
        // portal-web/docroot/html/taglib/ui/input_permissions/page.jsp
        serviceContext.setAddGroupPermissions(true);
        DLFolderServiceUtil.addFolder(
            groupId,
            repositoryId,
            mountPoint,
            parentFolderId,
            folderName,
            folderDescription,
            serviceContext);
        docLibModelBean.forceTreeRequery();
        logger.debug("Added folderName=[{0}] description=[{1}]", folderName, folderDescription);
      } catch (Exception e) {
        logger.error(e.getMessage(), e);
        liferayFacesContext.addGlobalUnexpectedErrorMessage();
      }

      docLibViewBean.setPopupRendered(false);
    }
  @Override
  public Folder addAttachmentsFolder() throws PortalException, SystemException {

    if (_attachmentsFolderId != DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) {

      return PortletFileRepositoryUtil.getPortletFolder(_attachmentsFolderId);
    }

    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setAddGroupPermissions(true);
    serviceContext.setAddGuestPermissions(true);

    Repository repository =
        PortletFileRepositoryUtil.addPortletRepository(
            getGroupId(), PortletKeys.MESSAGE_BOARDS, serviceContext);

    MBThread thread = getThread();

    Folder threadFolder = thread.addAttachmentsFolder();

    Folder folder =
        PortletFileRepositoryUtil.addPortletFolder(
            getUserId(),
            repository.getRepositoryId(),
            threadFolder.getFolderId(),
            String.valueOf(getMessageId()),
            serviceContext);

    _attachmentsFolderId = folder.getFolderId();

    return folder;
  }
  @Override
  public Folder addAttachmentsFolder() throws PortalException {
    if (_attachmentsFolderId != DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) {

      return PortletFileRepositoryUtil.getPortletFolder(_attachmentsFolderId);
    }

    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setAddGroupPermissions(true);
    serviceContext.setAddGuestPermissions(true);

    Repository repository =
        PortletFileRepositoryUtil.addPortletRepository(
            getGroupId(), PortletKeys.BACKGROUND_TASK, serviceContext);

    Folder folder =
        PortletFileRepositoryUtil.addPortletFolder(
            getUserId(),
            repository.getRepositoryId(),
            DLFolderConstants.DEFAULT_PARENT_FOLDER_ID,
            String.valueOf(getBackgroundTaskId()),
            serviceContext);

    _attachmentsFolderId = folder.getFolderId();

    return folder;
  }
  protected FileEntry addFileEntry(
      long folderId, String sourceFileName, String title, byte[] bytes, int workflowAction)
      throws Exception {

    String description = StringPool.BLANK;
    String changeLog = StringPool.BLANK;

    if ((bytes == null) && Validator.isNotNull(sourceFileName)) {
      bytes = CONTENT.getBytes();
    }

    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setAddGroupPermissions(true);
    serviceContext.setAddGuestPermissions(true);
    serviceContext.setWorkflowAction(workflowAction);

    return DLAppServiceUtil.addFileEntry(
        TestPropsValues.getGroupId(),
        folderId,
        sourceFileName,
        ContentTypes.TEXT_PLAIN,
        title,
        description,
        changeLog,
        bytes,
        serviceContext);
  }
  protected String[] readAssetTagNames(long userId, WikiNode node, String content)
      throws PortalException {

    Matcher matcher = _categoriesPattern.matcher(content);

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

    while (matcher.find()) {
      String categoryName = matcher.group(1);

      categoryName = normalize(categoryName, 75);

      AssetTag assetTag = null;

      try {
        assetTag = AssetTagLocalServiceUtil.getTag(node.getGroupId(), categoryName);
      } catch (NoSuchTagException nste) {
        ServiceContext serviceContext = new ServiceContext();

        serviceContext.setAddGroupPermissions(true);
        serviceContext.setAddGuestPermissions(true);
        serviceContext.setScopeGroupId(node.getGroupId());

        assetTag = AssetTagLocalServiceUtil.addTag(userId, categoryName, null, serviceContext);
      }

      assetTagNames.add(assetTag.getName());
    }

    if (content.contains(_WORK_IN_PROGRESS)) {
      assetTagNames.add(_WORK_IN_PROGRESS_TAG);
    }

    return assetTagNames.toArray(new String[assetTagNames.size()]);
  }
  @Before
  public void setUp() throws Exception {
    _group = ServiceTestUtil.addGroup();

    String name = "Test Folder";
    String description = "This is a test folder.";

    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setAddGroupPermissions(true);
    serviceContext.setAddGuestPermissions(true);
    serviceContext.setScopeGroupId(_group.getGroupId());

    try {
      DLAppServiceHttp.deleteFolder(
          TestPropsValues.getHttpPrincipal(),
          _group.getGroupId(),
          DLFolderConstants.DEFAULT_PARENT_FOLDER_ID,
          name);
    } catch (Exception e) {
    }

    _folder =
        DLAppServiceHttp.addFolder(
            TestPropsValues.getHttpPrincipal(),
            _group.getGroupId(),
            DLFolderConstants.DEFAULT_PARENT_FOLDER_ID,
            name,
            description,
            serviceContext);
  }
  protected void importAssetVocabulary(
      PortletDataContext portletDataContext,
      Map<Long, Long> assetVocabularyPKs,
      Element assetVocabularyElement,
      AssetVocabulary assetVocabulary)
      throws Exception {

    long userId = portletDataContext.getUserId(assetVocabulary.getUserUuid());
    long groupId = portletDataContext.getScopeGroupId();

    ServiceContext serviceContext = new ServiceContext();

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

    AssetVocabulary importedAssetVocabulary = null;

    AssetVocabulary existingAssetVocabulary =
        AssetVocabularyUtil.fetchByG_N(groupId, assetVocabulary.getName());

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

      existingAssetVocabulary =
          AssetVocabularyUtil.fetchByG_N(companyGroup.getGroupId(), assetVocabulary.getName());
    }

    if (existingAssetVocabulary == null) {
      serviceContext.setUuid(assetVocabulary.getUuid());

      importedAssetVocabulary =
          AssetVocabularyLocalServiceUtil.addVocabulary(
              userId,
              assetVocabulary.getTitle(),
              getAssetVocabularyTitleMap(assetVocabulary),
              assetVocabulary.getDescriptionMap(),
              assetVocabulary.getSettings(),
              serviceContext);
    } else {
      importedAssetVocabulary =
          AssetVocabularyLocalServiceUtil.updateVocabulary(
              existingAssetVocabulary.getVocabularyId(),
              assetVocabulary.getTitle(),
              getAssetVocabularyTitleMap(assetVocabulary),
              assetVocabulary.getDescriptionMap(),
              assetVocabulary.getSettings(),
              serviceContext);
    }

    assetVocabularyPKs.put(
        assetVocabulary.getVocabularyId(), importedAssetVocabulary.getVocabularyId());

    portletDataContext.importPermissions(
        AssetVocabulary.class,
        assetVocabulary.getVocabularyId(),
        importedAssetVocabulary.getVocabularyId());
  }
  protected FileEntry updateFileEntry(
      long fileEntryId, String sourceFileName, String title, boolean majorVersion)
      throws Exception {

    String description = StringPool.BLANK;
    String changeLog = StringPool.BLANK;

    byte[] bytes = null;

    if (Validator.isNotNull(sourceFileName)) {
      bytes = CONTENT.getBytes();
    }

    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setAddGroupPermissions(true);
    serviceContext.setAddGuestPermissions(true);

    return DLAppServiceUtil.updateFileEntry(
        fileEntryId,
        sourceFileName,
        ContentTypes.TEXT_PLAIN,
        title,
        description,
        changeLog,
        majorVersion,
        bytes,
        serviceContext);
  }
  public static Folder getGadgetEditorRootFolder(long repositoryId) throws Exception {

    Folder folder = null;

    try {
      folder =
          DLAppServiceUtil.getFolder(
              repositoryId,
              DLFolderConstants.DEFAULT_PARENT_FOLDER_ID,
              _GADGET_EDITOR_ROOT_FOLDER_NAME);
    } catch (Exception e) {
    }

    if (folder == null) {
      ServiceContext serviceContext = new ServiceContext();

      serviceContext.setAddGroupPermissions(true);
      serviceContext.setAddGuestPermissions(true);
      serviceContext.setScopeGroupId(repositoryId);

      folder =
          DLAppServiceUtil.addFolder(
              repositoryId,
              DLFolderConstants.DEFAULT_PARENT_FOLDER_ID,
              _GADGET_EDITOR_ROOT_FOLDER_NAME,
              StringPool.BLANK,
              serviceContext);
    }

    return folder;
  }
  @Override
  public long getAttachmentsFolderId() {
    if (_attachmentsFolderId != DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) {

      return _attachmentsFolderId;
    }

    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setAddGroupPermissions(true);
    serviceContext.setAddGuestPermissions(true);

    Repository repository =
        PortletFileRepositoryUtil.fetchPortletRepository(getGroupId(), PortletKeys.BACKGROUND_TASK);

    if (repository == null) {
      return DLFolderConstants.DEFAULT_PARENT_FOLDER_ID;
    }

    try {
      Folder folder =
          PortletFileRepositoryUtil.getPortletFolder(
              repository.getRepositoryId(),
              DLFolderConstants.DEFAULT_PARENT_FOLDER_ID,
              String.valueOf(getBackgroundTaskId()));

      _attachmentsFolderId = folder.getFolderId();
    } catch (Exception e) {
    }

    return _attachmentsFolderId;
  }
  protected void processSpecialPages(
      long userId, WikiNode node, Element rootElement, List<String> specialNamespaces)
      throws PortalException {

    ProgressTracker progressTracker = ProgressTrackerThreadLocal.getProgressTracker();

    List<Element> pageElements = rootElement.elements("page");

    for (int i = 0; i < pageElements.size(); i++) {
      Element pageElement = pageElements.get(i);

      String title = pageElement.elementText("title");

      if (!title.startsWith("Category:")) {
        if (isSpecialMediaWikiPage(title, specialNamespaces)) {
          rootElement.remove(pageElement);
        }

        continue;
      }

      String categoryName = title.substring("Category:".length());

      categoryName = normalize(categoryName, 75);

      Element revisionElement = pageElement.element("revision");

      String description = revisionElement.elementText("text");

      description = normalizeDescription(description);

      try {
        AssetTag assetTag = null;

        try {
          assetTag = AssetTagLocalServiceUtil.getTag(node.getCompanyId(), categoryName);
        } catch (NoSuchTagException nste) {
          ServiceContext serviceContext = new ServiceContext();

          serviceContext.setAddGroupPermissions(true);
          serviceContext.setAddGuestPermissions(true);
          serviceContext.setScopeGroupId(node.getGroupId());

          assetTag = AssetTagLocalServiceUtil.addTag(userId, categoryName, null, serviceContext);
        }

        if (Validator.isNotNull(description)) {
          AssetTagPropertyLocalServiceUtil.addTagProperty(
              userId, assetTag.getTagId(), "description", description);
        }
      } catch (SystemException se) {
        _log.error(se, se);
      }

      if ((i % 5) == 0) {
        progressTracker.setPercent((i * 10) / pageElements.size());
      }
    }
  }
  protected ServiceContext getServiceContext() {
    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setAddGroupPermissions(true);
    serviceContext.setAddGuestPermissions(true);

    return serviceContext;
  }
  protected void testUserPermissions(
      boolean addBaseModelPermission, boolean addParentBaseModelPermission) throws Exception {

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

    SearchContext searchContext = SearchContextTestUtil.getSearchContext(group.getGroupId());

    searchContext.setKeywords(getSearchKeywords());

    int initialBaseModelsSearchCount =
        searchBaseModelsCount(getBaseModelClass(), group.getGroupId(), searchContext);

    serviceContext.setAddGroupPermissions(addParentBaseModelPermission);
    serviceContext.setAddGuestPermissions(addParentBaseModelPermission);

    BaseModel<?> parentBaseModel = getParentBaseModel(group, serviceContext);

    serviceContext.setAddGroupPermissions(addBaseModelPermission);
    serviceContext.setAddGuestPermissions(addBaseModelPermission);

    baseModel = addBaseModel(parentBaseModel, true, getSearchKeywords(), serviceContext);

    User user = UserTestUtil.addUser(null, 0);

    PermissionChecker originalPermissionChecker = PermissionThreadLocal.getPermissionChecker();

    try {
      PermissionChecker permissionChecker = PermissionCheckerFactoryUtil.create(user);

      PermissionThreadLocal.setPermissionChecker(permissionChecker);

      searchContext.setUserId(user.getUserId());

      int baseModelsCount = initialBaseModelsSearchCount;

      if (addBaseModelPermission && !isCheckBaseModelPermission()) {
        baseModelsCount++;
      }

      Assert.assertEquals(
          baseModelsCount,
          searchBaseModelsCount(getBaseModelClass(), group.getGroupId(), searchContext));
    } finally {
      PermissionThreadLocal.setPermissionChecker(originalPermissionChecker);
    }
  }
  protected DLFileShortcut addDLFileShortcut(FileEntry fileEntry, long folderId) throws Exception {

    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setAddGroupPermissions(true);
    serviceContext.setAddGuestPermissions(true);

    return DLAppServiceUtil.addFileShortcut(
        TestPropsValues.getGroupId(), folderId, fileEntry.getFileEntryId(), serviceContext);
  }
  @Override
  public FileEntry addPortletFileEntry(
      long groupId,
      long userId,
      String className,
      long classPK,
      String portletId,
      long folderId,
      File file,
      String fileName,
      String mimeType,
      boolean indexingEnabled)
      throws PortalException, SystemException {

    if (Validator.isNull(fileName)) {
      return null;
    }

    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setAddGroupPermissions(true);
    serviceContext.setAddGuestPermissions(true);

    Repository repository = addPortletRepository(groupId, portletId, serviceContext);

    serviceContext.setAttribute("className", className);
    serviceContext.setAttribute("classPK", String.valueOf(classPK));
    serviceContext.setIndexingEnabled(indexingEnabled);

    if (Validator.isNull(mimeType) || mimeType.equals(ContentTypes.APPLICATION_OCTET_STREAM)) {

      mimeType = MimeTypesUtil.getContentType(file, fileName);
    }

    boolean dlAppHelperEnabled = DLAppHelperThreadLocal.isEnabled();

    try {
      DLAppHelperThreadLocal.setEnabled(false);

      return DLAppLocalServiceUtil.addFileEntry(
          userId,
          repository.getRepositoryId(),
          folderId,
          fileName,
          mimeType,
          fileName,
          StringPool.BLANK,
          StringPool.BLANK,
          file,
          serviceContext);
    } finally {
      DLAppHelperThreadLocal.setEnabled(dlAppHelperEnabled);
    }
  }
  protected ServiceContext createServiceContext(
      PortletDataContext portletDataContext, AssetTag assetTag) {

    ServiceContext serviceContext = new ServiceContext();

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

    return serviceContext;
  }
  protected DLFileRank addDLFileRank(long fileEntryId) throws Exception {
    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setAddGroupPermissions(true);
    serviceContext.setAddGuestPermissions(true);

    return DLAppLocalServiceUtil.addFileRank(
        TestPropsValues.getGroupId(),
        TestPropsValues.getCompanyId(),
        TestPropsValues.getUserId(),
        fileEntryId,
        serviceContext);
  }
  @Test
  public void testAddFileEntryWithInvalidMimeType() throws Exception {
    long folderId = parentFolder.getFolderId();
    String description = StringPool.BLANK;
    String changeLog = StringPool.BLANK;

    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setAddGroupPermissions(true);
    serviceContext.setAddGuestPermissions(true);
    serviceContext.setScopeGroupId(group.getGroupId());

    try {
      String name = "InvalidMime.txt";
      byte[] bytes = CONTENT.getBytes();

      FileEntry fileEntry =
          DLAppServiceUtil.addFileEntry(
              group.getGroupId(),
              folderId,
              name,
              ContentTypes.APPLICATION_OCTET_STREAM,
              name,
              description,
              changeLog,
              bytes,
              serviceContext);

      Assert.assertEquals(ContentTypes.TEXT_PLAIN, fileEntry.getMimeType());

      name = "InvalidMime";

      fileEntry =
          DLAppServiceUtil.updateFileEntry(
              fileEntry.getFileEntryId(),
              name,
              null,
              name,
              description,
              changeLog,
              true,
              bytes,
              serviceContext);

      Assert.assertEquals(ContentTypes.TEXT_PLAIN, fileEntry.getMimeType());
    } catch (Exception e) {
      Assert.fail("Unable to add file with invalid mime type " + StackTraceUtil.getStackTrace(e));
    }
  }
Example #19
0
  public static int addResource(WebDAVRequest webDavRequest, long classNameId) throws Exception {

    String[] pathArray = webDavRequest.getPathArray();

    if (pathArray.length != 4) {
      return HttpServletResponse.SC_FORBIDDEN;
    }

    String type = pathArray[2];
    String typeId = pathArray[3];

    if (type.equals(TYPE_STRUCTURES)) {
      HttpServletRequest request = webDavRequest.getHttpServletRequest();

      String xsd = StringUtil.read(request.getInputStream());

      String defaultLocale = LocalizationUtil.getDefaultLocale(xsd);

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

      nameMap.put(LocaleUtil.fromLanguageId(defaultLocale), typeId);

      ServiceContext serviceContext = new ServiceContext();

      serviceContext.setAddGroupPermissions(true);
      serviceContext.setAddGuestPermissions(true);

      DDMStructureLocalServiceUtil.addStructure(
          webDavRequest.getUserId(),
          webDavRequest.getGroupId(),
          classNameId,
          nameMap,
          null,
          xsd,
          serviceContext);

      return HttpServletResponse.SC_CREATED;
    } else if (type.equals(TYPE_TEMPLATES)) {

      // DDM templates can not be added via WebDAV because there is no way
      // to know the associated class name or class PK

      return HttpServletResponse.SC_FORBIDDEN;
    }

    return HttpServletResponse.SC_FORBIDDEN;
  }
  /**
   * Returns a new service context object identical to this service context object.
   *
   * @return a new service context object
   */
  @Override
  public Object clone() {
    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setAddGroupPermissions(isAddGroupPermissions());
    serviceContext.setAddGuestPermissions(isAddGuestPermissions());
    serviceContext.setAssetCategoryIds(getAssetCategoryIds());
    serviceContext.setAssetEntryVisible(isAssetEntryVisible());
    serviceContext.setAssetLinkEntryIds(getAssetLinkEntryIds());
    serviceContext.setAssetTagNames(getAssetTagNames());
    serviceContext.setAttributes(getAttributes());
    serviceContext.setCommand(getCommand());
    serviceContext.setCompanyId(getCompanyId());
    serviceContext.setCreateDate(getCreateDate());
    serviceContext.setCurrentURL(getCurrentURL());
    serviceContext.setExpandoBridgeAttributes(getExpandoBridgeAttributes());
    serviceContext.setFailOnPortalException(isFailOnPortalException());
    serviceContext.setGroupPermissions(getGroupPermissions());
    serviceContext.setGuestPermissions(getGuestPermissions());
    serviceContext.setHeaders(getHeaders());
    serviceContext.setIndexingEnabled(isIndexingEnabled());
    serviceContext.setLanguageId(getLanguageId());
    serviceContext.setLayoutFullURL(getLayoutFullURL());
    serviceContext.setLayoutURL(getLayoutURL());
    serviceContext.setModifiedDate(getModifiedDate());
    serviceContext.setPathFriendlyURLPrivateGroup(getPathFriendlyURLPrivateGroup());
    serviceContext.setPathFriendlyURLPrivateUser(getPathFriendlyURLPrivateUser());
    serviceContext.setPathFriendlyURLPublic(getPathFriendlyURLPublic());
    serviceContext.setPathMain(getPathMain());
    serviceContext.setPlid(getPlid());
    serviceContext.setPortalURL(getPortalURL());
    serviceContext.setPortletPreferencesIds(getPortletPreferencesIds());
    serviceContext.setRemoteAddr(getRemoteAddr());
    serviceContext.setRemoteHost(getRemoteHost());
    serviceContext.setRequest(getRequest());
    serviceContext.setScopeGroupId(getScopeGroupId());
    serviceContext.setSignedIn(isSignedIn());
    serviceContext.setUserDisplayURL(getUserDisplayURL());
    serviceContext.setUserId(getUserId());
    serviceContext.setUuid(getUuid());
    serviceContext.setWorkflowAction(getWorkflowAction());

    return serviceContext;
  }
Example #21
0
  /**
   * Returns the tags matching the group and names, creating new tags with the names if the group
   * doesn't already have them.
   *
   * <p>For each name, if a tag with that name doesn't already exist for the group, this method
   * creates a new tag with that name for the group. If a tag with that name already exists in the
   * company group, this method copies that company group's tag's properties to the group's new tag.
   *
   * @param userId the primary key of the user
   * @param group ID the primary key of the tag's group
   * @param names the tag names
   * @return the tags matching the group and names and new tags matching the names that don't
   *     already exist for the group
   * @throws PortalException if a matching group could not be found, if the tag's key or value were
   *     invalid, or if a portal exception occurred
   * @throws SystemException if a system exception occurred
   */
  @Override
  public List<AssetTag> checkTags(long userId, Group group, String[] names)
      throws PortalException, SystemException {

    List<AssetTag> tags = new ArrayList<AssetTag>();

    for (String name : names) {
      AssetTag tag = null;

      try {
        tag = getTag(group.getGroupId(), name);
      } catch (NoSuchTagException nste1) {
        ServiceContext serviceContext = new ServiceContext();

        serviceContext.setAddGroupPermissions(true);
        serviceContext.setAddGuestPermissions(true);
        serviceContext.setScopeGroupId(group.getGroupId());

        tag = addTag(userId, name, PropsValues.ASSET_TAG_PROPERTIES_DEFAULT, serviceContext);

        Group companyGroup = groupLocalService.getCompanyGroup(group.getCompanyId());

        try {
          AssetTag companyGroupTag = getTag(companyGroup.getGroupId(), name);

          List<AssetTagProperty> tagProperties =
              assetTagPropertyLocalService.getTagProperties(companyGroupTag.getTagId());

          for (AssetTagProperty tagProperty : tagProperties) {
            assetTagPropertyLocalService.addTagProperty(
                userId, tag.getTagId(), tagProperty.getKey(), tagProperty.getValue());
          }
        } catch (NoSuchTagException nste2) {
        }
      }

      if (tag != null) {
        tags.add(tag);
      }
    }

    return tags;
  }
  protected Folder addFolder(long parentFolderId, String name, boolean deleteExisting)
      throws Exception {

    String description = StringPool.BLANK;

    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setAddGroupPermissions(true);
    serviceContext.setAddGuestPermissions(true);

    if (deleteExisting) {
      try {
        DLAppServiceUtil.deleteFolder(TestPropsValues.getGroupId(), parentFolderId, name);
      } catch (NoSuchFolderException nsfe) {
      }
    }

    return DLAppServiceUtil.addFolder(
        TestPropsValues.getGroupId(), parentFolderId, name, description, serviceContext);
  }
  @Override
  public long getAttachmentsFolderId() throws PortalException, SystemException {

    if (_attachmentsFolderId != DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) {

      return _attachmentsFolderId;
    }

    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setAddGroupPermissions(true);
    serviceContext.setAddGuestPermissions(true);

    Repository repository =
        PortletFileRepositoryUtil.fetchPortletRepository(getGroupId(), PortletKeys.MESSAGE_BOARDS);

    long threadAttachmetsFolderId = getThreadAttachmentsFolderId();

    if ((repository == null)
        || (threadAttachmetsFolderId == DLFolderConstants.DEFAULT_PARENT_FOLDER_ID)) {

      return DLFolderConstants.DEFAULT_PARENT_FOLDER_ID;
    }

    try {
      Folder folder =
          PortletFileRepositoryUtil.getPortletFolder(
              getUserId(),
              repository.getRepositoryId(),
              threadAttachmetsFolderId,
              String.valueOf(getMessageId()),
              serviceContext);

      _attachmentsFolderId = folder.getFolderId();
    } catch (Exception e) {
    }

    return _attachmentsFolderId;
  }
Example #24
0
  protected FileEntry addFileEntry(String title) throws Exception {
    long folderId = _folder.getFolderId();
    String description = StringPool.BLANK;
    String changeLog = StringPool.BLANK;
    byte[] bytes = _CONTENT.getBytes();

    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setAddGroupPermissions(true);
    serviceContext.setAddGuestPermissions(true);

    return DLAppServiceHttp.addFileEntry(
        TestPropsValues.getHttpPrincipal(),
        TestPropsValues.getGroupId(),
        folderId,
        title,
        ContentTypes.TEXT_PLAIN,
        title,
        description,
        changeLog,
        bytes,
        serviceContext);
  }
  protected void moveFrontPage(long userId, WikiNode node, Map<String, String[]> options) {

    String frontPageTitle = MapUtil.getString(options, WikiImporterKeys.OPTIONS_FRONT_PAGE);

    if (Validator.isNotNull(frontPageTitle)) {
      frontPageTitle = normalizeTitle(frontPageTitle);

      try {
        if (WikiPageLocalServiceUtil.getPagesCount(node.getNodeId(), frontPageTitle, true) > 0) {

          ServiceContext serviceContext = new ServiceContext();

          serviceContext.setAddGroupPermissions(true);
          serviceContext.setAddGuestPermissions(true);

          WikiPageLocalServiceUtil.movePage(
              userId,
              node.getNodeId(),
              frontPageTitle,
              WikiPageConstants.FRONT_PAGE,
              false,
              serviceContext);
        }
      } catch (Exception e) {
        if (_log.isWarnEnabled()) {
          StringBundler sb = new StringBundler(4);

          sb.append("Could not move ");
          sb.append(WikiPageConstants.FRONT_PAGE);
          sb.append(" to the title provided: ");
          sb.append(frontPageTitle);

          _log.warn(sb.toString(), e);
        }
      }
    }
  }
  @Override
  public CalendarResource addCalendarResource(
      long userId,
      long groupId,
      long classNameId,
      long classPK,
      String classUuid,
      String code,
      Map<Locale, String> nameMap,
      Map<Locale, String> descriptionMap,
      boolean active,
      ServiceContext serviceContext)
      throws PortalException {

    // Calendar resource

    User user = userPersistence.findByPrimaryKey(userId);

    long calendarResourceId = counterLocalService.increment();

    if (classNameId == classNameLocalService.getClassNameId(CalendarResource.class)) {

      classPK = calendarResourceId;
    }

    if (PortletPropsValues.CALENDAR_RESOURCE_FORCE_AUTOGENERATE_CODE || Validator.isNull(code)) {

      code = String.valueOf(calendarResourceId);
    } else {
      code = code.trim();
      code = StringUtil.toUpperCase(code);
    }

    Date now = new Date();

    validate(groupId, classNameId, classPK, code, nameMap);

    CalendarResource calendarResource = calendarResourcePersistence.create(calendarResourceId);

    calendarResource.setUuid(serviceContext.getUuid());
    calendarResource.setGroupId(groupId);
    calendarResource.setCompanyId(user.getCompanyId());
    calendarResource.setUserId(user.getUserId());
    calendarResource.setUserName(user.getFullName());
    calendarResource.setCreateDate(serviceContext.getCreateDate(now));
    calendarResource.setModifiedDate(serviceContext.getModifiedDate(now));
    calendarResource.setClassNameId(classNameId);
    calendarResource.setClassPK(classPK);
    calendarResource.setClassUuid(classUuid);
    calendarResource.setCode(code);
    calendarResource.setNameMap(nameMap);
    calendarResource.setDescriptionMap(descriptionMap);
    calendarResource.setActive(active);

    calendarResourcePersistence.update(calendarResource);

    // Resources

    resourceLocalService.addModelResources(calendarResource, serviceContext);

    // Calendar

    if (!ExportImportThreadLocal.isImportInProcess()) {
      serviceContext.setAddGroupPermissions(true);
      serviceContext.setAddGuestPermissions(true);

      calendarLocalService.addCalendar(
          userId,
          calendarResource.getGroupId(),
          calendarResourceId,
          nameMap,
          descriptionMap,
          calendarResource.getTimeZoneId(),
          PortletPropsValues.CALENDAR_COLOR_DEFAULT,
          true,
          false,
          false,
          serviceContext);
    }

    // Asset

    updateAsset(
        calendarResource.getUserId(),
        calendarResource,
        serviceContext.getAssetCategoryIds(),
        serviceContext.getAssetTagNames());

    return calendarResource;
  }
  protected void processImages(long userId, WikiNode node, InputStream imagesInputStream)
      throws Exception {

    if (imagesInputStream == null) {
      return;
    }

    ProgressTracker progressTracker = ProgressTrackerThreadLocal.getProgressTracker();

    int count = 0;

    ZipReader zipReader = ZipReaderFactoryUtil.getZipReader(imagesInputStream);

    List<String> entries = zipReader.getEntries();

    int total = entries.size();

    if (total > 0) {
      try {
        WikiPageLocalServiceUtil.getPage(node.getNodeId(), SHARED_IMAGES_TITLE);
      } catch (NoSuchPageException nspe) {
        ServiceContext serviceContext = new ServiceContext();

        serviceContext.setAddGroupPermissions(true);
        serviceContext.setAddGuestPermissions(true);

        WikiPageLocalServiceUtil.addPage(
            userId,
            node.getNodeId(),
            SHARED_IMAGES_TITLE,
            SHARED_IMAGES_CONTENT,
            null,
            true,
            serviceContext);
      }
    }

    List<ObjectValuePair<String, InputStream>> inputStreamOVPs =
        new ArrayList<ObjectValuePair<String, InputStream>>();

    try {
      int percentage = 50;

      for (int i = 0; i < entries.size(); i++) {
        String entry = entries.get(i);

        String key = entry;

        InputStream inputStream = zipReader.getEntryAsInputStream(entry);

        String[] paths = StringUtil.split(key, CharPool.SLASH);

        if (!isValidImage(paths, inputStream)) {
          if (_log.isInfoEnabled()) {
            _log.info("Ignoring " + key);
          }

          continue;
        }

        String fileName = StringUtil.toLowerCase(paths[paths.length - 1]);

        ObjectValuePair<String, InputStream> inputStreamOVP =
            new ObjectValuePair<String, InputStream>(fileName, inputStream);

        inputStreamOVPs.add(inputStreamOVP);

        count++;

        if ((i % 5) == 0) {
          WikiPageLocalServiceUtil.addPageAttachments(
              userId, node.getNodeId(), SHARED_IMAGES_TITLE, inputStreamOVPs);

          inputStreamOVPs.clear();

          percentage = Math.min(50 + (i * 50) / total, 99);

          progressTracker.setPercent(percentage);
        }
      }

      if (!inputStreamOVPs.isEmpty()) {
        WikiPageLocalServiceUtil.addPageAttachments(
            userId, node.getNodeId(), SHARED_IMAGES_TITLE, inputStreamOVPs);
      }
    } finally {
      for (ObjectValuePair<String, InputStream> inputStreamOVP : inputStreamOVPs) {

        InputStream inputStream = inputStreamOVP.getValue();

        StreamUtil.cleanUp(inputStream);
      }
    }

    zipReader.close();

    if (_log.isInfoEnabled()) {
      _log.info("Imported " + count + " images into " + node.getName());
    }
  }
  @Test
  public void testAsstTags() throws Exception {
    long folderId = parentFolder.getFolderId();
    String name = "TestTags.txt";
    String description = StringPool.BLANK;
    String changeLog = StringPool.BLANK;
    byte[] bytes = CONTENT.getBytes();

    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setAddGroupPermissions(true);
    serviceContext.setAddGuestPermissions(true);
    serviceContext.setScopeGroupId(group.getGroupId());

    String[] assetTagNames = new String[] {"hello", "world"};

    serviceContext.setAssetTagNames(assetTagNames);

    FileEntry fileEntry =
        DLAppServiceUtil.addFileEntry(
            group.getGroupId(),
            folderId,
            name,
            ContentTypes.TEXT_PLAIN,
            name,
            description,
            changeLog,
            bytes,
            serviceContext);

    AssetEntry assetEntry =
        AssetEntryLocalServiceUtil.fetchEntry(
            DLFileEntryConstants.getClassName(), fileEntry.getFileEntryId());

    AssertUtils.assertEqualsSorted(assetTagNames, assetEntry.getTagNames());

    Thread.sleep(1000 * TestPropsValues.JUNIT_DELAY_FACTOR);

    _fileEntry = fileEntry;

    search(_fileEntry, false, "hello", true);
    search(_fileEntry, false, "world", true);
    search(_fileEntry, false, "liferay", false);

    assetTagNames = new String[] {"hello", "world", "liferay"};

    serviceContext.setAssetTagNames(assetTagNames);

    fileEntry =
        DLAppServiceUtil.updateFileEntry(
            fileEntry.getFileEntryId(),
            name,
            ContentTypes.TEXT_PLAIN,
            name,
            description,
            changeLog,
            false,
            bytes,
            serviceContext);

    assetEntry =
        AssetEntryLocalServiceUtil.fetchEntry(
            DLFileEntryConstants.getClassName(), fileEntry.getFileEntryId());

    AssertUtils.assertEqualsSorted(assetTagNames, assetEntry.getTagNames());

    Thread.sleep(1000 * TestPropsValues.JUNIT_DELAY_FACTOR);

    _fileEntry = fileEntry;

    search(_fileEntry, false, "hello", true);
    search(_fileEntry, false, "world", true);
    search(_fileEntry, false, "liferay", true);

    DLAppServiceUtil.deleteFileEntry(_fileEntry.getFileEntryId());

    _fileEntry = null;
  }
  @Test
  public void testAddNullFileEntry() throws Exception {
    long folderId = parentFolder.getFolderId();
    String description = StringPool.BLANK;
    String changeLog = StringPool.BLANK;

    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setAddGroupPermissions(true);
    serviceContext.setAddGuestPermissions(true);
    serviceContext.setScopeGroupId(group.getGroupId());

    try {
      String name = "Bytes-null.txt";
      byte[] bytes = null;

      FileEntry fileEntry =
          DLAppServiceUtil.addFileEntry(
              group.getGroupId(),
              folderId,
              name,
              ContentTypes.TEXT_PLAIN,
              name,
              description,
              changeLog,
              bytes,
              serviceContext);

      DLAppServiceUtil.updateFileEntry(
          fileEntry.getFileEntryId(),
          name,
          ContentTypes.TEXT_PLAIN,
          name,
          description,
          changeLog,
          true,
          bytes,
          serviceContext);

      String newName = "Bytes-changed.txt";

      bytes = CONTENT.getBytes();

      DLAppServiceUtil.updateFileEntry(
          fileEntry.getFileEntryId(),
          newName,
          ContentTypes.TEXT_PLAIN,
          newName,
          description,
          changeLog,
          true,
          bytes,
          serviceContext);
    } catch (Exception e) {
      Assert.fail("Unable to pass null byte[] " + StackTraceUtil.getStackTrace(e));
    }

    try {
      String name = "File-null.txt";
      File file = null;

      FileEntry fileEntry =
          DLAppServiceUtil.addFileEntry(
              group.getGroupId(),
              folderId,
              name,
              ContentTypes.TEXT_PLAIN,
              name,
              description,
              changeLog,
              file,
              serviceContext);

      DLAppServiceUtil.updateFileEntry(
          fileEntry.getFileEntryId(),
          name,
          ContentTypes.TEXT_PLAIN,
          name,
          description,
          changeLog,
          true,
          file,
          serviceContext);

      try {
        String newName = "File-changed.txt";

        file = FileUtil.createTempFile(CONTENT.getBytes());

        DLAppServiceUtil.updateFileEntry(
            fileEntry.getFileEntryId(),
            newName,
            ContentTypes.TEXT_PLAIN,
            newName,
            description,
            changeLog,
            true,
            file,
            serviceContext);
      } finally {
        FileUtil.delete(file);
      }
    } catch (Exception e) {
      Assert.fail("Unable to pass null File " + StackTraceUtil.getStackTrace(e));
    }

    try {
      String name = "IS-null.txt";
      InputStream is = null;

      FileEntry fileEntry =
          DLAppServiceUtil.addFileEntry(
              group.getGroupId(),
              folderId,
              name,
              ContentTypes.TEXT_PLAIN,
              name,
              description,
              changeLog,
              is,
              0,
              serviceContext);

      DLAppServiceUtil.updateFileEntry(
          fileEntry.getFileEntryId(),
          name,
          ContentTypes.TEXT_PLAIN,
          name,
          description,
          changeLog,
          true,
          is,
          0,
          serviceContext);

      try {
        String newName = "IS-changed.txt";

        is = new ByteArrayInputStream(CONTENT.getBytes());

        DLAppServiceUtil.updateFileEntry(
            fileEntry.getFileEntryId(),
            newName,
            ContentTypes.TEXT_PLAIN,
            newName,
            description,
            changeLog,
            true,
            is,
            0,
            serviceContext);
      } finally {
        if (is != null) {
          is.close();
        }
      }
    } catch (Exception e) {
      Assert.fail("Unable to pass null InputStream " + StackTraceUtil.getStackTrace(e));
    }
  }
  protected ServiceContext createServiceContext(
      Element element, String path, ClassedModel classedModel, String namespace) {

    Class<?> clazz = classedModel.getModelClass();
    long classPK = getClassPK(classedModel);

    ServiceContext serviceContext = new ServiceContext();

    // Theme display

    serviceContext.setCompanyId(getCompanyId());
    serviceContext.setScopeGroupId(getScopeGroupId());

    // Dates

    if (classedModel instanceof AuditedModel) {
      AuditedModel auditedModel = (AuditedModel) classedModel;

      serviceContext.setCreateDate(auditedModel.getCreateDate());
      serviceContext.setModifiedDate(auditedModel.getModifiedDate());
    }

    // Permissions

    if (!MapUtil.getBoolean(_parameterMap, PortletDataHandlerKeys.PERMISSIONS)) {

      serviceContext.setAddGroupPermissions(true);
      serviceContext.setAddGuestPermissions(true);
    }

    // Asset

    boolean portletMetadataAll =
        getBooleanParameter(namespace, PortletDataHandlerKeys.PORTLET_METADATA_ALL);

    if (isResourceMain(classedModel)) {
      if (portletMetadataAll || getBooleanParameter(namespace, "categories")) {

        long[] assetCategoryIds = getAssetCategoryIds(clazz, classPK);

        serviceContext.setAssetCategoryIds(assetCategoryIds);
      }

      if (portletMetadataAll || getBooleanParameter(namespace, "tags")) {
        String[] assetTagNames = getAssetTagNames(clazz, classPK);

        serviceContext.setAssetTagNames(assetTagNames);
      }
    }

    // Expando

    String expandoPath = null;

    if (element != null) {
      expandoPath = element.attributeValue("expando-path");
    } else {
      expandoPath = getExpandoPath(path);
    }

    if (Validator.isNotNull(expandoPath)) {
      try {
        Map<String, Serializable> expandoBridgeAttributes =
            (Map<String, Serializable>) getZipEntryAsObject(expandoPath);

        serviceContext.setExpandoBridgeAttributes(expandoBridgeAttributes);
      } catch (Exception e) {
        if (_log.isDebugEnabled()) {
          _log.debug(e, e);
        }
      }
    }

    return serviceContext;
  }