001    /**
002     * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
013     */
014    
015    package com.liferay.portlet.usersadmin.action;
016    
017    import com.liferay.portal.kernel.bean.BeanPropertiesUtil;
018    import com.liferay.portal.kernel.dao.orm.QueryUtil;
019    import com.liferay.portal.kernel.servlet.ServletResponseUtil;
020    import com.liferay.portal.kernel.servlet.SessionErrors;
021    import com.liferay.portal.kernel.util.CSVUtil;
022    import com.liferay.portal.kernel.util.ContentTypes;
023    import com.liferay.portal.kernel.util.OrderByComparator;
024    import com.liferay.portal.kernel.util.ParamUtil;
025    import com.liferay.portal.kernel.util.ProgressTracker;
026    import com.liferay.portal.kernel.util.StringBundler;
027    import com.liferay.portal.kernel.util.StringPool;
028    import com.liferay.portal.kernel.workflow.WorkflowConstants;
029    import com.liferay.portal.model.User;
030    import com.liferay.portal.security.permission.ActionKeys;
031    import com.liferay.portal.security.permission.PermissionChecker;
032    import com.liferay.portal.service.UserLocalServiceUtil;
033    import com.liferay.portal.service.permission.PortalPermissionUtil;
034    import com.liferay.portal.service.permission.PortletPermissionUtil;
035    import com.liferay.portal.struts.ActionConstants;
036    import com.liferay.portal.struts.PortletAction;
037    import com.liferay.portal.theme.ThemeDisplay;
038    import com.liferay.portal.util.PortalUtil;
039    import com.liferay.portal.util.PortletKeys;
040    import com.liferay.portal.util.PropsValues;
041    import com.liferay.portal.util.WebKeys;
042    import com.liferay.portlet.ActionResponseImpl;
043    import com.liferay.portlet.expando.model.ExpandoBridge;
044    import com.liferay.portlet.usersadmin.search.UserSearch;
045    import com.liferay.portlet.usersadmin.search.UserSearchTerms;
046    
047    import java.util.Collections;
048    import java.util.Iterator;
049    import java.util.LinkedHashMap;
050    import java.util.List;
051    
052    import javax.portlet.ActionRequest;
053    import javax.portlet.ActionResponse;
054    import javax.portlet.PortletConfig;
055    import javax.portlet.PortletURL;
056    
057    import javax.servlet.http.HttpServletRequest;
058    import javax.servlet.http.HttpServletResponse;
059    
060    import org.apache.struts.action.ActionForm;
061    import org.apache.struts.action.ActionMapping;
062    
063    /**
064     * @author Brian Wing Shun Chan
065     * @author Mika Koivisto
066     */
067    public class ExportUsersAction extends PortletAction {
068    
069            @Override
070            public void processAction(
071                            ActionMapping mapping, ActionForm form, PortletConfig portletConfig,
072                            ActionRequest actionRequest, ActionResponse actionResponse)
073                    throws Exception {
074    
075                    try {
076                            String csv = getUsersCSV(actionRequest, actionResponse);
077    
078                            String fileName = "users.csv";
079                            byte[] bytes = csv.getBytes();
080    
081                            HttpServletRequest request = PortalUtil.getHttpServletRequest(
082                                    actionRequest);
083                            HttpServletResponse response = PortalUtil.getHttpServletResponse(
084                                    actionResponse);
085    
086                            ServletResponseUtil.sendFile(
087                                    request, response, fileName, bytes, ContentTypes.TEXT_CSV_UTF8);
088    
089                            setForward(actionRequest, ActionConstants.COMMON_NULL);
090                    }
091                    catch (Exception e) {
092                            SessionErrors.add(actionRequest, e.getClass());
093    
094                            setForward(actionRequest, "portlet.users_admin.error");
095                    }
096            }
097    
098            protected String getUserCSV(User user) {
099                    StringBundler sb = new StringBundler(
100                            PropsValues.USERS_EXPORT_CSV_FIELDS.length * 2);
101    
102                    for (int i = 0; i < PropsValues.USERS_EXPORT_CSV_FIELDS.length; i++) {
103                            String field = PropsValues.USERS_EXPORT_CSV_FIELDS[i];
104    
105                            if (field.equals("fullName")) {
106                                    sb.append(CSVUtil.encode(user.getFullName()));
107                            }
108                            else if (field.startsWith("expando:")) {
109                                    String attributeName = field.substring(8);
110    
111                                    ExpandoBridge expandoBridge = user.getExpandoBridge();
112    
113                                    sb.append(
114                                            CSVUtil.encode(expandoBridge.getAttribute(attributeName)));
115                            }
116                            else {
117                                    sb.append(
118                                            CSVUtil.encode(BeanPropertiesUtil.getString(user, field)));
119                            }
120    
121                            if ((i + 1) < PropsValues.USERS_EXPORT_CSV_FIELDS.length) {
122                                    sb.append(StringPool.COMMA);
123                            }
124                    }
125    
126                    sb.append(StringPool.NEW_LINE);
127    
128                    return sb.toString();
129            }
130    
131            protected List<User> getUsers(
132                            ActionRequest actionRequest, ActionResponse actionResponse)
133                    throws Exception {
134    
135                    ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(
136                            WebKeys.THEME_DISPLAY);
137    
138                    PermissionChecker permissionChecker =
139                            themeDisplay.getPermissionChecker();
140    
141                    boolean exportAllUsers = PortalPermissionUtil.contains(
142                            permissionChecker, ActionKeys.EXPORT_USER);
143    
144                    if (!exportAllUsers &&
145                            !PortletPermissionUtil.contains(
146                                    permissionChecker, PortletKeys.USERS_ADMIN,
147                                    ActionKeys.EXPORT_USER)) {
148    
149                            return Collections.emptyList();
150                    }
151    
152                    PortletURL portletURL =
153                            ((ActionResponseImpl)actionResponse).createRenderURL(
154                                    PortletKeys.USERS_ADMIN);
155    
156                    UserSearch userSearch = new UserSearch(actionRequest, portletURL);
157    
158                    UserSearchTerms searchTerms =
159                            (UserSearchTerms)userSearch.getSearchTerms();
160    
161                    searchTerms.setStatus(WorkflowConstants.STATUS_APPROVED);
162    
163                    LinkedHashMap<String, Object> params =
164                            new LinkedHashMap<String, Object>();
165    
166                    long organizationId = searchTerms.getOrganizationId();
167    
168                    if (organizationId > 0) {
169                            params.put("usersOrgs", new Long(organizationId));
170                    }
171                    else if (!exportAllUsers) {
172                            User user = themeDisplay.getUser();
173    
174                            long[] organizationIds = user.getOrganizationIds(true);
175    
176                            if (organizationIds.length > 0) {
177                                    params.put("usersOrgs", organizationIds);
178                            }
179                    }
180    
181                    long roleId = searchTerms.getRoleId();
182    
183                    if (roleId > 0) {
184                            params.put("usersRoles", new Long(roleId));
185                    }
186    
187                    long userGroupId = searchTerms.getUserGroupId();
188    
189                    if (userGroupId > 0) {
190                            params.put("usersUserGroups", new Long(userGroupId));
191                    }
192    
193                    if (searchTerms.isAdvancedSearch()) {
194                            return UserLocalServiceUtil.search(
195                                    themeDisplay.getCompanyId(), searchTerms.getFirstName(),
196                                    searchTerms.getMiddleName(), searchTerms.getLastName(),
197                                    searchTerms.getScreenName(), searchTerms.getEmailAddress(),
198                                    searchTerms.getStatus(), params, searchTerms.isAndOperator(),
199                                    QueryUtil.ALL_POS, QueryUtil.ALL_POS, (OrderByComparator)null);
200                    }
201                    else {
202                            return UserLocalServiceUtil.search(
203                                    themeDisplay.getCompanyId(), searchTerms.getKeywords(),
204                                    searchTerms.getStatus(), params, QueryUtil.ALL_POS,
205                                    QueryUtil.ALL_POS, (OrderByComparator)null);
206                    }
207            }
208    
209            protected String getUsersCSV(
210                            ActionRequest actionRequest, ActionResponse actionResponse)
211                    throws Exception {
212    
213                    List<User> users = getUsers(actionRequest, actionResponse);
214    
215                    if (users.isEmpty()) {
216                            return StringPool.BLANK;
217                    }
218    
219                    String exportProgressId = ParamUtil.getString(
220                            actionRequest, "exportProgressId");
221    
222                    ProgressTracker progressTracker = new ProgressTracker(
223                            actionRequest, exportProgressId);
224    
225                    progressTracker.start();
226    
227                    int percentage = 10;
228                    int total = users.size();
229    
230                    progressTracker.updateProgress(percentage);
231    
232                    StringBundler sb = new StringBundler(users.size() * 4);
233    
234                    Iterator<User> itr = users.iterator();
235    
236                    for (int i = 0; itr.hasNext(); i++) {
237                            User user = itr.next();
238    
239                            sb.append(getUserCSV(user));
240    
241                            percentage = Math.min(10 + (i * 90) / total, 99);
242    
243                            progressTracker.updateProgress(percentage);
244                    }
245    
246                    progressTracker.finish();
247    
248                    return sb.toString();
249            }
250    
251    }