Search in sources :

Example 31 with ServiceContext

use of com.liferay.portal.service.ServiceContext in project liferay-ide by liferay.

the class JukeboxPortlet method addAlbum.

public void addAlbum(ActionRequest request, ActionResponse response) throws Exception {
    UploadPortletRequest uploadPortletRequest = PortalUtil.getUploadPortletRequest(request);
    long artistId = ParamUtil.getLong(uploadPortletRequest, "artistId");
    String name = ParamUtil.getString(uploadPortletRequest, "name");
    int year = ParamUtil.getInteger(uploadPortletRequest, "year");
    InputStream inputStream = uploadPortletRequest.getFileAsStream("file");
    ServiceContext serviceContext = ServiceContextFactory.getInstance(Album.class.getName(), uploadPortletRequest);
    try {
        AlbumServiceUtil.addAlbum(artistId, name, year, inputStream, serviceContext);
        SessionMessages.add(request, "albumAdded");
        String redirect = ParamUtil.getString(uploadPortletRequest, "redirect");
        response.sendRedirect(redirect);
    } catch (Exception e) {
        SessionErrors.add(request, e.getClass().getName());
        if (e instanceof AlbumNameException || e instanceof PrincipalException) {
            response.setRenderParameter("jspPage", "/html/albums/edit_album.jsp");
        } else {
            response.setRenderParameter("jspPage", "/html/error.jsp");
        }
    }
}
Also used : InputStream(java.io.InputStream) ServiceContext(com.liferay.portal.service.ServiceContext) PrincipalException(com.liferay.portal.security.auth.PrincipalException) Album(org.liferay.jukebox.model.Album) UploadPortletRequest(com.liferay.portal.kernel.upload.UploadPortletRequest) AlbumNameException(org.liferay.jukebox.AlbumNameException) SongNameException(org.liferay.jukebox.SongNameException) PrincipalException(com.liferay.portal.security.auth.PrincipalException) DuplicatedSongException(org.liferay.jukebox.DuplicatedSongException) AlbumNameException(org.liferay.jukebox.AlbumNameException) ArtistNameException(org.liferay.jukebox.ArtistNameException)

Example 32 with ServiceContext

use of com.liferay.portal.service.ServiceContext in project liferay-ide by liferay.

the class BaseKBPortlet method updateKBArticle.

public void updateKBArticle(ActionRequest actionRequest, ActionResponse actionResponse) throws Exception {
    String portletId = PortalUtil.getPortletId(actionRequest);
    String cmd = ParamUtil.getString(actionRequest, Constants.CMD);
    long resourcePrimKey = ParamUtil.getLong(actionRequest, "resourcePrimKey");
    long parentResourceClassNameId = ParamUtil.getLong(actionRequest, "parentResourceClassNameId", PortalUtil.getClassNameId(KBFolderConstants.getClassName()));
    long parentResourcePrimKey = ParamUtil.getLong(actionRequest, "parentResourcePrimKey", KBFolderConstants.DEFAULT_PARENT_FOLDER_ID);
    String title = ParamUtil.getString(actionRequest, "title");
    String urlTitle = ParamUtil.getString(actionRequest, "urlTitle");
    String content = ParamUtil.getString(actionRequest, "content");
    String description = ParamUtil.getString(actionRequest, "description");
    String sourceURL = ParamUtil.getString(actionRequest, "sourceURL");
    String[] sections = actionRequest.getParameterValues("sections");
    String[] selectedFileNames = ParamUtil.getParameterValues(actionRequest, "selectedFileName");
    long[] removeFileEntryIds = ParamUtil.getLongValues(actionRequest, "removeFileEntryIds");
    int workflowAction = ParamUtil.getInteger(actionRequest, "workflowAction");
    KBArticle kbArticle = null;
    ServiceContext serviceContext = ServiceContextFactory.getInstance(KBArticle.class.getName(), actionRequest);
    if (cmd.equals(Constants.ADD)) {
        kbArticle = KBArticleServiceUtil.addKBArticle(portletId, parentResourceClassNameId, parentResourcePrimKey, title, urlTitle, content, description, sourceURL, sections, selectedFileNames, serviceContext);
    } else if (cmd.equals(Constants.UPDATE)) {
        kbArticle = KBArticleServiceUtil.updateKBArticle(resourcePrimKey, title, content, description, sourceURL, sections, selectedFileNames, removeFileEntryIds, serviceContext);
    }
    if (!cmd.equals(Constants.ADD) && !cmd.equals(Constants.UPDATE)) {
        return;
    }
    if (workflowAction == WorkflowConstants.ACTION_SAVE_DRAFT) {
        String editURL = buildEditURL(actionRequest, actionResponse, kbArticle);
        actionRequest.setAttribute(WebKeys.REDIRECT, editURL);
    }
}
Also used : KBArticle(com.liferay.knowledgebase.model.KBArticle) ServiceContext(com.liferay.portal.service.ServiceContext)

Example 33 with ServiceContext

use of com.liferay.portal.service.ServiceContext in project liferay-ide by liferay.

the class KBArticleAttachmentsUtil method updateAttachments.

public static void updateAttachments(KBArticle kbArticle) {
    try {
        long folderId = kbArticle.getClassPK();
        String oldDirName = "knowledgebase/articles/" + folderId;
        String newDirName = "knowledgebase/kbarticles/" + folderId;
        DLStoreUtil.addDirectory(kbArticle.getCompanyId(), CompanyConstants.SYSTEM, newDirName);
        String[] fileNames = DLStoreUtil.getFileNames(kbArticle.getCompanyId(), CompanyConstants.SYSTEM, oldDirName);
        ServiceContext serviceContext = new ServiceContext();
        serviceContext.setCompanyId(kbArticle.getCompanyId());
        serviceContext.setScopeGroupId(kbArticle.getGroupId());
        for (String fileName : fileNames) {
            String shortFileName = FileUtil.getShortFileName(fileName);
            byte[] bytes = DLStoreUtil.getFileAsBytes(kbArticle.getCompanyId(), CompanyConstants.SYSTEM, fileName);
            DLStoreUtil.addFile(kbArticle.getCompanyId(), CompanyConstants.SYSTEM, newDirName + StringPool.SLASH + shortFileName, bytes);
        }
        DLStoreUtil.deleteDirectory(kbArticle.getCompanyId(), CompanyConstants.SYSTEM, oldDirName);
        if (_log.isInfoEnabled()) {
            _log.info("Added attachments for " + folderId);
        }
    } catch (Exception e) {
        _log.error(e.getMessage());
    }
}
Also used : ServiceContext(com.liferay.portal.service.ServiceContext)

Example 34 with ServiceContext

use of com.liferay.portal.service.ServiceContext in project liferay-ide by liferay.

the class UserLocalServiceImpl method addDefaultAdminUser.

/**
 * Adds a default admin user for the company.
 *
 * @param  companyId the primary key of the user's company
 * @param  screenName the user's screen name
 * @param  emailAddress the user's email address
 * @param  locale the user's locale
 * @param  firstName the user's first name
 * @param  middleName the user's middle name
 * @param  lastName the user's last name
 * @return the new default admin user
 * @throws PortalException n if a portal exception occurred
 * @throws SystemException if a system exception occurred
 */
@Override
public User addDefaultAdminUser(long companyId, String screenName, String emailAddress, Locale locale, String firstName, String middleName, String lastName) throws PortalException, SystemException {
    long creatorUserId = 0;
    boolean autoPassword = false;
    String password1 = PropsValues.DEFAULT_ADMIN_PASSWORD;
    String password2 = password1;
    boolean autoScreenName = false;
    screenName = getLogin(screenName);
    for (int i = 1; ; i++) {
        User screenNameUser = userPersistence.fetchByC_SN(companyId, screenName);
        if (screenNameUser == null) {
            break;
        }
        screenName = screenName + i;
    }
    long facebookId = 0;
    String openId = StringPool.BLANK;
    int prefixId = 0;
    int suffixId = 0;
    boolean male = true;
    int birthdayMonth = Calendar.JANUARY;
    int birthdayDay = 1;
    int birthdayYear = 1970;
    String jobTitle = StringPool.BLANK;
    Group guestGroup = groupLocalService.getGroup(companyId, GroupConstants.GUEST);
    long[] groupIds = { guestGroup.getGroupId() };
    long[] organizationIds = null;
    Role adminRole = roleLocalService.getRole(companyId, RoleConstants.ADMINISTRATOR);
    Role powerUserRole = roleLocalService.getRole(companyId, RoleConstants.POWER_USER);
    long[] roleIds = { adminRole.getRoleId(), powerUserRole.getRoleId() };
    long[] userGroupIds = null;
    boolean sendEmail = false;
    ServiceContext serviceContext = new ServiceContext();
    User defaultAdminUser = addUser(creatorUserId, companyId, autoPassword, password1, password2, autoScreenName, screenName, emailAddress, facebookId, openId, locale, firstName, middleName, lastName, prefixId, suffixId, male, birthdayMonth, birthdayDay, birthdayYear, jobTitle, groupIds, organizationIds, roleIds, userGroupIds, sendEmail, serviceContext);
    updateEmailAddressVerified(defaultAdminUser.getUserId(), true);
    updateLastLogin(defaultAdminUser.getUserId(), defaultAdminUser.getLoginIP());
    updatePasswordReset(defaultAdminUser.getUserId(), false);
    return defaultAdminUser;
}
Also used : Role(com.liferay.portal.model.Role) UserGroupRole(com.liferay.portal.model.UserGroupRole) Group(com.liferay.portal.model.Group) UserGroup(com.liferay.portal.model.UserGroup) User(com.liferay.portal.model.User) ServiceContext(com.liferay.portal.service.ServiceContext)

Example 35 with ServiceContext

use of com.liferay.portal.service.ServiceContext in project liferay-ide by liferay.

the class UserLocalServiceImpl method addUserWithWorkflow.

/**
 * Adds a user with workflow.
 *
 * <p>
 * This method handles the creation and bookkeeping of the user including
 * its resources, metadata, and internal data structures. It is not
 * necessary to make subsequent calls to any methods to setup default
 * groups, resources, etc.
 * </p>
 *
 * @param  creatorUserId the primary key of the creator
 * @param  companyId the primary key of the user's company
 * @param  autoPassword whether a password should be automatically generated
 *         for the user
 * @param  password1 the user's password
 * @param  password2 the user's password confirmation
 * @param  autoScreenName whether a screen name should be automatically
 *         generated for the user
 * @param  screenName the user's screen name
 * @param  emailAddress the user's email address
 * @param  facebookId the user's facebook ID
 * @param  openId the user's OpenID
 * @param  locale the user's locale
 * @param  firstName the user's first name
 * @param  middleName the user's middle name
 * @param  lastName the user's last name
 * @param  prefixId the user's name prefix ID
 * @param  suffixId the user's name suffix ID
 * @param  male whether the user is male
 * @param  birthdayMonth the user's birthday month (0-based, meaning 0 for
 *         January)
 * @param  birthdayDay the user's birthday day
 * @param  birthdayYear the user's birthday year
 * @param  jobTitle the user's job title
 * @param  groupIds the primary keys of the user's groups
 * @param  organizationIds the primary keys of the user's organizations
 * @param  roleIds the primary keys of the roles this user possesses
 * @param  userGroupIds the primary keys of the user's user groups
 * @param  sendEmail whether to send the user an email notification about
 *         their new account
 * @param  serviceContext the service context to be applied (optionally
 *         <code>null</code>). Can set the UUID (with the <code>uuid</code>
 *         attribute), asset category IDs, asset tag names, and expando
 *         bridge attributes for the user.
 * @return the new user
 * @throws PortalException if the user's information was invalid
 * @throws SystemException if a system exception occurred
 */
@Override
@SuppressWarnings("deprecation")
public User addUserWithWorkflow(long creatorUserId, long companyId, boolean autoPassword, String password1, String password2, boolean autoScreenName, String screenName, String emailAddress, long facebookId, String openId, Locale locale, String firstName, String middleName, String lastName, int prefixId, int suffixId, boolean male, int birthdayMonth, int birthdayDay, int birthdayYear, String jobTitle, long[] groupIds, long[] organizationIds, long[] roleIds, long[] userGroupIds, boolean sendEmail, ServiceContext serviceContext) throws PortalException, SystemException {
    // User
    Company company = companyPersistence.findByPrimaryKey(companyId);
    screenName = getLogin(screenName);
    openId = StringUtil.trim(openId);
    Date now = new Date();
    if (PrefsPropsUtil.getBoolean(companyId, PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
        autoScreenName = true;
    }
    // PLACEHOLDER 01
    long userId = counterLocalService.increment();
    EmailAddressGenerator emailAddressGenerator = EmailAddressGeneratorFactory.getInstance();
    if ((emailAddress == null) || emailAddressGenerator.isGenerated(emailAddress)) {
        emailAddress = StringPool.BLANK;
    } else {
        emailAddress = StringUtil.toLowerCase(emailAddress.trim());
    }
    if (!PrefsPropsUtil.getBoolean(companyId, PropsKeys.USERS_EMAIL_ADDRESS_REQUIRED) && Validator.isNull(emailAddress)) {
        emailAddress = emailAddressGenerator.generate(companyId, userId);
    }
    validate(companyId, userId, autoPassword, password1, password2, autoScreenName, screenName, emailAddress, openId, firstName, middleName, lastName, organizationIds);
    if (!autoPassword) {
        if (Validator.isNull(password1) || Validator.isNull(password2)) {
            throw new UserPasswordException(UserPasswordException.PASSWORD_INVALID);
        }
    }
    if (autoScreenName) {
        ScreenNameGenerator screenNameGenerator = ScreenNameGeneratorFactory.getInstance();
        try {
            screenName = screenNameGenerator.generate(companyId, userId, emailAddress);
        } catch (Exception e) {
            throw new SystemException(e);
        }
    }
    User defaultUser = getDefaultUser(companyId);
    FullNameGenerator fullNameGenerator = FullNameGeneratorFactory.getInstance();
    String fullName = fullNameGenerator.getFullName(firstName, middleName, lastName);
    String greeting = LanguageUtil.format(locale, "welcome-x", " " + fullName, false);
    User user = userPersistence.create(userId);
    if (serviceContext != null) {
        String uuid = serviceContext.getUuid();
        if (Validator.isNotNull(uuid)) {
            user.setUuid(uuid);
        }
    }
    user.setCompanyId(companyId);
    user.setCreateDate(now);
    user.setModifiedDate(now);
    user.setDefaultUser(false);
    user.setContactId(counterLocalService.increment());
    if (Validator.isNotNull(password1)) {
        user.setPassword(PasswordEncryptorUtil.encrypt(password1));
        user.setPasswordUnencrypted(password1);
    }
    user.setPasswordEncrypted(true);
    PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
    boolean passwordReset = false;
    if (passwordPolicy != null) {
        if (passwordPolicy.isChangeable() && passwordPolicy.isChangeRequired()) {
            passwordReset = true;
        }
        addPasswordPolicyUsers(passwordPolicy.getPasswordPolicyId(), new long[] { userId });
    }
    user.setPasswordReset(passwordReset);
    user.setDigest(StringPool.BLANK);
    user.setScreenName(screenName);
    user.setEmailAddress(emailAddress);
    user.setFacebookId(facebookId);
    Long ldapServerId = (Long) serviceContext.getAttribute("ldapServerId");
    if (ldapServerId != null) {
        user.setLdapServerId(ldapServerId);
    } else {
        user.setLdapServerId(-1);
    }
    user.setOpenId(openId);
    user.setLanguageId(LocaleUtil.toLanguageId(locale));
    user.setTimeZoneId(defaultUser.getTimeZoneId());
    user.setGreeting(greeting);
    user.setFirstName(firstName);
    user.setMiddleName(middleName);
    user.setLastName(lastName);
    user.setJobTitle(jobTitle);
    user.setStatus(WorkflowConstants.STATUS_DRAFT);
    user.setExpandoBridgeAttributes(serviceContext);
    userPersistence.update(user, serviceContext);
    // Contact
    String creatorUserName = StringPool.BLANK;
    if (creatorUserId <= 0) {
        creatorUserId = user.getUserId();
    // Don't grab the full name from the User object because it doesn't
    // have a corresponding Contact object yet
    // creatorUserName = user.getFullName();
    } else {
        User creatorUser = userPersistence.findByPrimaryKey(creatorUserId);
        creatorUserName = creatorUser.getFullName();
    }
    Date birthday = getBirthday(birthdayMonth, birthdayDay, birthdayYear);
    Contact contact = contactPersistence.create(user.getContactId());
    contact.setCompanyId(user.getCompanyId());
    contact.setUserId(creatorUserId);
    contact.setUserName(creatorUserName);
    contact.setCreateDate(now);
    contact.setModifiedDate(now);
    contact.setClassName(User.class.getName());
    contact.setClassPK(user.getUserId());
    contact.setAccountId(company.getAccountId());
    contact.setParentContactId(ContactConstants.DEFAULT_PARENT_CONTACT_ID);
    contact.setEmailAddress(user.getEmailAddress());
    contact.setFirstName(firstName);
    contact.setMiddleName(middleName);
    contact.setLastName(lastName);
    contact.setPrefixId(prefixId);
    contact.setSuffixId(suffixId);
    contact.setMale(male);
    contact.setBirthday(birthday);
    contact.setJobTitle(jobTitle);
    contactPersistence.update(contact, serviceContext);
    // Group
    groupLocalService.addGroup(user.getUserId(), GroupConstants.DEFAULT_PARENT_GROUP_ID, User.class.getName(), user.getUserId(), null, null, 0, StringPool.SLASH + screenName, false, true, null);
    if (groupIds != null) {
        List<Group> groups = new ArrayList<Group>();
        for (long groupId : groupIds) {
            Group group = groupLocalService.fetchGroup(groupId);
            if (group != null) {
                groups.add(group);
            } else {
                if (_log.isWarnEnabled()) {
                    _log.warn("Group " + groupId + " does not exist");
                }
            }
        }
        groupLocalService.addUserGroups(userId, groups);
    }
    addDefaultGroups(userId);
    // Organizations
    updateOrganizations(userId, organizationIds, false);
    if (roleIds != null) {
        roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
        userPersistence.setRoles(userId, roleIds);
    }
    addDefaultRoles(userId);
    if (userGroupIds != null) {
        if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
            for (long userGroupId : userGroupIds) {
                userGroupLocalService.copyUserGroupLayouts(userGroupId, new long[] { userId });
            }
        }
        userPersistence.setUserGroups(userId, userGroupIds);
    }
    addDefaultUserGroups(userId);
    // Resources
    resourceLocalService.addResources(companyId, 0, creatorUserId, User.class.getName(), user.getUserId(), false, false, false);
    if (serviceContext != null) {
        updateAsset(creatorUserId, user, serviceContext.getAssetCategoryIds(), serviceContext.getAssetTagNames());
    }
    if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
        reindex(user);
    }
    // Workflow
    long workflowUserId = creatorUserId;
    if (workflowUserId == userId) {
        workflowUserId = defaultUser.getUserId();
    }
    ServiceContext workflowServiceContext = serviceContext;
    if (workflowServiceContext == null) {
        workflowServiceContext = new ServiceContext();
    }
    workflowServiceContext.setAttribute("autoPassword", autoPassword);
    workflowServiceContext.setAttribute("passwordUnencrypted", password1);
    workflowServiceContext.setAttribute("sendEmail", sendEmail);
    WorkflowHandlerRegistryUtil.startWorkflowInstance(companyId, workflowUserId, User.class.getName(), userId, user, workflowServiceContext);
    if (serviceContext != null) {
        String passwordUnencrypted = (String) serviceContext.getAttribute("passwordUnencrypted");
        if (Validator.isNotNull(passwordUnencrypted)) {
            user.setPasswordUnencrypted(passwordUnencrypted);
        }
    }
    return user;
}
Also used : Group(com.liferay.portal.model.Group) UserGroup(com.liferay.portal.model.UserGroup) Company(com.liferay.portal.model.Company) User(com.liferay.portal.model.User) ScreenNameGenerator(com.liferay.portal.security.auth.ScreenNameGenerator) ServiceContext(com.liferay.portal.service.ServiceContext) ArrayList(java.util.ArrayList) Date(java.util.Date) ContactFirstNameException(com.liferay.portal.ContactFirstNameException) ModelListenerException(com.liferay.portal.ModelListenerException) NoSuchImageException(com.liferay.portal.NoSuchImageException) GroupFriendlyURLException(com.liferay.portal.GroupFriendlyURLException) DuplicateOpenIdException(com.liferay.portal.DuplicateOpenIdException) ImageSizeException(com.liferay.portlet.documentlibrary.ImageSizeException) PasswordExpiredException(com.liferay.portal.PasswordExpiredException) UserPasswordException(com.liferay.portal.UserPasswordException) NoSuchUserException(com.liferay.portal.NoSuchUserException) UserSmsException(com.liferay.portal.UserSmsException) NoSuchRoleException(com.liferay.portal.NoSuchRoleException) PortalException(com.liferay.portal.kernel.exception.PortalException) UserIdException(com.liferay.portal.UserIdException) UserPortraitTypeException(com.liferay.portal.UserPortraitTypeException) RequiredUserException(com.liferay.portal.RequiredUserException) ReservedUserScreenNameException(com.liferay.portal.ReservedUserScreenNameException) IOException(java.io.IOException) ContactBirthdayException(com.liferay.portal.ContactBirthdayException) UserReminderQueryException(com.liferay.portal.UserReminderQueryException) DuplicateUserScreenNameException(com.liferay.portal.DuplicateUserScreenNameException) UserEmailAddressException(com.liferay.portal.UserEmailAddressException) ContactFullNameException(com.liferay.portal.ContactFullNameException) EncryptorException(com.liferay.util.EncryptorException) CompanyMaxUsersException(com.liferay.portal.CompanyMaxUsersException) NoSuchTicketException(com.liferay.portal.NoSuchTicketException) UserScreenNameException(com.liferay.portal.UserScreenNameException) ContactLastNameException(com.liferay.portal.ContactLastNameException) ReservedUserEmailAddressException(com.liferay.portal.ReservedUserEmailAddressException) DuplicateUserEmailAddressException(com.liferay.portal.DuplicateUserEmailAddressException) NoSuchUserGroupException(com.liferay.portal.NoSuchUserGroupException) PrincipalException(com.liferay.portal.security.auth.PrincipalException) SystemException(com.liferay.portal.kernel.exception.SystemException) NoSuchOrganizationException(com.liferay.portal.NoSuchOrganizationException) UserLockoutException(com.liferay.portal.UserLockoutException) UserPortraitSizeException(com.liferay.portal.UserPortraitSizeException) Contact(com.liferay.portal.model.Contact) EmailAddressGenerator(com.liferay.portal.security.auth.EmailAddressGenerator) SystemException(com.liferay.portal.kernel.exception.SystemException) UserPasswordException(com.liferay.portal.UserPasswordException) FullNameGenerator(com.liferay.portal.security.auth.FullNameGenerator) PasswordPolicy(com.liferay.portal.model.PasswordPolicy)

Aggregations

ServiceContext (com.liferay.portal.service.ServiceContext)57 User (com.liferay.portal.model.User)11 PrincipalException (com.liferay.portal.security.auth.PrincipalException)11 InputStream (java.io.InputStream)11 AlbumNameException (org.liferay.jukebox.AlbumNameException)9 ArtistNameException (org.liferay.jukebox.ArtistNameException)9 DuplicatedSongException (org.liferay.jukebox.DuplicatedSongException)9 SongNameException (org.liferay.jukebox.SongNameException)9 UploadPortletRequest (com.liferay.portal.kernel.upload.UploadPortletRequest)8 Song (org.liferay.jukebox.model.Song)8 ThemeDisplay (com.liferay.portal.theme.ThemeDisplay)7 Date (java.util.Date)7 SystemException (com.liferay.portal.kernel.exception.SystemException)6 FileEntry (com.liferay.portal.kernel.repository.model.FileEntry)6 PortalException (com.liferay.portal.kernel.exception.PortalException)5 JSONObject (com.liferay.portal.kernel.json.JSONObject)5 Artist (org.liferay.jukebox.model.Artist)5 Gadget (com.liferay.opensocial.model.Gadget)4 Folder (com.liferay.portal.kernel.repository.model.Folder)4 Element (com.liferay.portal.kernel.xml.Element)4