001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
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.search.Hits;
020    import com.liferay.portal.kernel.search.Sort;
021    import com.liferay.portal.kernel.servlet.ServletResponseUtil;
022    import com.liferay.portal.kernel.servlet.SessionErrors;
023    import com.liferay.portal.kernel.util.ArrayUtil;
024    import com.liferay.portal.kernel.util.CSVUtil;
025    import com.liferay.portal.kernel.util.ContentTypes;
026    import com.liferay.portal.kernel.util.OrderByComparator;
027    import com.liferay.portal.kernel.util.ParamUtil;
028    import com.liferay.portal.kernel.util.ProgressTracker;
029    import com.liferay.portal.kernel.util.StringBundler;
030    import com.liferay.portal.kernel.util.StringPool;
031    import com.liferay.portal.kernel.util.Tuple;
032    import com.liferay.portal.model.User;
033    import com.liferay.portal.security.permission.ActionKeys;
034    import com.liferay.portal.security.permission.PermissionChecker;
035    import com.liferay.portal.service.UserLocalServiceUtil;
036    import com.liferay.portal.service.permission.PortalPermissionUtil;
037    import com.liferay.portal.service.permission.PortletPermissionUtil;
038    import com.liferay.portal.struts.ActionConstants;
039    import com.liferay.portal.struts.PortletAction;
040    import com.liferay.portal.theme.ThemeDisplay;
041    import com.liferay.portal.util.PortalUtil;
042    import com.liferay.portal.util.PortletKeys;
043    import com.liferay.portal.util.PropsValues;
044    import com.liferay.portal.util.WebKeys;
045    import com.liferay.portlet.ActionResponseImpl;
046    import com.liferay.portlet.expando.model.ExpandoBridge;
047    import com.liferay.portlet.usersadmin.search.UserSearch;
048    import com.liferay.portlet.usersadmin.search.UserSearchTerms;
049    import com.liferay.portlet.usersadmin.util.UsersAdminUtil;
050    
051    import java.util.Collections;
052    import java.util.LinkedHashMap;
053    import java.util.List;
054    
055    import javax.portlet.ActionRequest;
056    import javax.portlet.ActionResponse;
057    import javax.portlet.PortletConfig;
058    import javax.portlet.PortletURL;
059    
060    import javax.servlet.http.HttpServletRequest;
061    import javax.servlet.http.HttpServletResponse;
062    
063    import org.apache.struts.action.ActionForm;
064    import org.apache.struts.action.ActionMapping;
065    
066    /**
067     * @author Brian Wing Shun Chan
068     * @author Mika Koivisto
069     */
070    public class ExportUsersAction extends PortletAction {
071    
072            @Override
073            public void processAction(
074                            ActionMapping mapping, ActionForm form, PortletConfig portletConfig,
075                            ActionRequest actionRequest, ActionResponse actionResponse)
076                    throws Exception {
077    
078                    try {
079                            String csv = getUsersCSV(actionRequest, actionResponse);
080    
081                            String fileName = "users.csv";
082                            byte[] bytes = csv.getBytes();
083    
084                            HttpServletRequest request = PortalUtil.getHttpServletRequest(
085                                    actionRequest);
086                            HttpServletResponse response = PortalUtil.getHttpServletResponse(
087                                    actionResponse);
088    
089                            ServletResponseUtil.sendFile(
090                                    request, response, fileName, bytes, ContentTypes.TEXT_CSV_UTF8);
091    
092                            setForward(actionRequest, ActionConstants.COMMON_NULL);
093                    }
094                    catch (Exception e) {
095                            SessionErrors.add(actionRequest, e.getClass());
096    
097                            setForward(actionRequest, "portlet.users_admin.error");
098                    }
099            }
100    
101            protected String getUserCSV(User user) {
102                    StringBundler sb = new StringBundler(
103                            PropsValues.USERS_EXPORT_CSV_FIELDS.length * 2);
104    
105                    for (int i = 0; i < PropsValues.USERS_EXPORT_CSV_FIELDS.length; i++) {
106                            String field = PropsValues.USERS_EXPORT_CSV_FIELDS[i];
107    
108                            if (field.equals("fullName")) {
109                                    sb.append(CSVUtil.encode(user.getFullName()));
110                            }
111                            else if (field.startsWith("expando:")) {
112                                    String attributeName = field.substring(8);
113    
114                                    ExpandoBridge expandoBridge = user.getExpandoBridge();
115    
116                                    sb.append(
117                                            CSVUtil.encode(expandoBridge.getAttribute(attributeName)));
118                            }
119                            else {
120                                    sb.append(
121                                            CSVUtil.encode(BeanPropertiesUtil.getString(user, field)));
122                            }
123    
124                            if ((i + 1) < PropsValues.USERS_EXPORT_CSV_FIELDS.length) {
125                                    sb.append(StringPool.COMMA);
126                            }
127                    }
128    
129                    sb.append(StringPool.NEW_LINE);
130    
131                    return sb.toString();
132            }
133    
134            protected List<User> getUsers(
135                            ActionRequest actionRequest, ActionResponse actionResponse)
136                    throws Exception {
137    
138                    ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(
139                            WebKeys.THEME_DISPLAY);
140    
141                    PermissionChecker permissionChecker =
142                            themeDisplay.getPermissionChecker();
143    
144                    boolean exportAllUsers = PortalPermissionUtil.contains(
145                            permissionChecker, ActionKeys.EXPORT_USER);
146    
147                    if (!exportAllUsers &&
148                            !PortletPermissionUtil.contains(
149                                    permissionChecker, PortletKeys.USERS_ADMIN,
150                                    ActionKeys.EXPORT_USER)) {
151    
152                            return Collections.emptyList();
153                    }
154    
155                    PortletURL portletURL =
156                            ((ActionResponseImpl)actionResponse).createRenderURL(
157                                    PortletKeys.USERS_ADMIN);
158    
159                    UserSearch userSearch = new UserSearch(actionRequest, portletURL);
160    
161                    UserSearchTerms searchTerms =
162                            (UserSearchTerms)userSearch.getSearchTerms();
163    
164                    LinkedHashMap<String, Object> params =
165                            new LinkedHashMap<String, Object>();
166    
167                    long organizationId = searchTerms.getOrganizationId();
168    
169                    if (organizationId > 0) {
170                            params.put("usersOrgs", new Long(organizationId));
171                    }
172                    else if (!exportAllUsers) {
173                            User user = themeDisplay.getUser();
174    
175                            Long[] organizationIds = ArrayUtil.toArray(
176                                    user.getOrganizationIds(true));
177    
178                            if (organizationIds.length > 0) {
179                                    params.put("usersOrgs", organizationIds);
180                            }
181                    }
182    
183                    long roleId = searchTerms.getRoleId();
184    
185                    if (roleId > 0) {
186                            params.put("usersRoles", new Long(roleId));
187                    }
188    
189                    long userGroupId = searchTerms.getUserGroupId();
190    
191                    if (userGroupId > 0) {
192                            params.put("usersUserGroups", new Long(userGroupId));
193                    }
194    
195                    if (PropsValues.USERS_INDEXER_ENABLED &&
196                            PropsValues.USERS_SEARCH_WITH_INDEX) {
197    
198                            params.put("expandoAttributes", searchTerms.getKeywords());
199    
200                            Hits hits = null;
201    
202                            if (searchTerms.isAdvancedSearch()) {
203                                    hits = UserLocalServiceUtil.search(
204                                            themeDisplay.getCompanyId(), searchTerms.getFirstName(),
205                                            searchTerms.getMiddleName(), searchTerms.getLastName(),
206                                            searchTerms.getScreenName(), searchTerms.getEmailAddress(),
207                                            searchTerms.getStatus(), params,
208                                            searchTerms.isAndOperator(), QueryUtil.ALL_POS,
209                                            QueryUtil.ALL_POS, (Sort)null);
210                            }
211                            else {
212                                    hits = UserLocalServiceUtil.search(
213                                            themeDisplay.getCompanyId(), searchTerms.getKeywords(),
214                                            searchTerms.getStatus(), params, QueryUtil.ALL_POS,
215                                            QueryUtil.ALL_POS, (Sort)null);
216                            }
217    
218                            Tuple tuple = UsersAdminUtil.getUsers(hits);
219    
220                            return (List<User>)tuple.getObject(0);
221                    }
222                    else {
223                            if (searchTerms.isAdvancedSearch()) {
224                                    return UserLocalServiceUtil.search(
225                                            themeDisplay.getCompanyId(), searchTerms.getFirstName(),
226                                            searchTerms.getMiddleName(), searchTerms.getLastName(),
227                                            searchTerms.getScreenName(), searchTerms.getEmailAddress(),
228                                            searchTerms.getStatus(), params,
229                                            searchTerms.isAndOperator(), QueryUtil.ALL_POS,
230                                            QueryUtil.ALL_POS, (OrderByComparator)null);
231                            }
232                            else {
233                                    return UserLocalServiceUtil.search(
234                                            themeDisplay.getCompanyId(), searchTerms.getKeywords(),
235                                            searchTerms.getStatus(), params, QueryUtil.ALL_POS,
236                                            QueryUtil.ALL_POS, (OrderByComparator)null);
237                            }
238                    }
239            }
240    
241            protected String getUsersCSV(
242                            ActionRequest actionRequest, ActionResponse actionResponse)
243                    throws Exception {
244    
245                    List<User> users = getUsers(actionRequest, actionResponse);
246    
247                    if (users.isEmpty()) {
248                            return StringPool.BLANK;
249                    }
250    
251                    String exportProgressId = ParamUtil.getString(
252                            actionRequest, "exportProgressId");
253    
254                    ProgressTracker progressTracker = new ProgressTracker(
255                            actionRequest, exportProgressId);
256    
257                    progressTracker.start();
258    
259                    int percentage = 10;
260                    int total = users.size();
261    
262                    progressTracker.setPercent(percentage);
263    
264                    StringBundler sb = new StringBundler(users.size());
265    
266                    for (int i = 0; i < users.size(); i++ ) {
267                            User user = users.get(i);
268    
269                            sb.append(getUserCSV(user));
270    
271                            percentage = Math.min(10 + (i * 90) / total, 99);
272    
273                            progressTracker.setPercent(percentage);
274                    }
275    
276                    progressTracker.finish();
277    
278                    return sb.toString();
279            }
280    
281    }