001    /**
002     * Copyright (c) 2000-2012 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.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.struts.ActionConstants;
035    import com.liferay.portal.struts.PortletAction;
036    import com.liferay.portal.theme.ThemeDisplay;
037    import com.liferay.portal.util.PortalUtil;
038    import com.liferay.portal.util.PortletKeys;
039    import com.liferay.portal.util.PropsValues;
040    import com.liferay.portal.util.WebKeys;
041    import com.liferay.portlet.ActionResponseImpl;
042    import com.liferay.portlet.expando.model.ExpandoBridge;
043    import com.liferay.portlet.usersadmin.search.UserSearch;
044    import com.liferay.portlet.usersadmin.search.UserSearchTerms;
045    
046    import java.util.Iterator;
047    import java.util.LinkedHashMap;
048    import java.util.List;
049    
050    import javax.portlet.ActionRequest;
051    import javax.portlet.ActionResponse;
052    import javax.portlet.PortletConfig;
053    import javax.portlet.PortletURL;
054    
055    import javax.servlet.http.HttpServletRequest;
056    import javax.servlet.http.HttpServletResponse;
057    
058    import org.apache.struts.action.ActionForm;
059    import org.apache.struts.action.ActionMapping;
060    
061    /**
062     * @author Brian Wing Shun Chan
063     * @author Mika Koivisto
064     */
065    public class ExportUsersAction extends PortletAction {
066    
067            @Override
068            public void processAction(
069                            ActionMapping mapping, ActionForm form, PortletConfig portletConfig,
070                            ActionRequest actionRequest, ActionResponse actionResponse)
071                    throws Exception {
072    
073                    try {
074                            String csv = getUsersCSV(actionRequest, actionResponse);
075    
076                            String fileName = "users.csv";
077                            byte[] bytes = csv.getBytes();
078    
079                            HttpServletRequest request = PortalUtil.getHttpServletRequest(
080                                    actionRequest);
081                            HttpServletResponse response = PortalUtil.getHttpServletResponse(
082                                    actionResponse);
083    
084                            ServletResponseUtil.sendFile(
085                                    request, response, fileName, bytes, ContentTypes.TEXT_CSV_UTF8);
086    
087                            setForward(actionRequest, ActionConstants.COMMON_NULL);
088                    }
089                    catch (Exception e) {
090                            SessionErrors.add(actionRequest, e.getClass().getName());
091    
092                            setForward(actionRequest, "portlet.users_admin.error");
093                    }
094            }
095    
096            protected String getUserCSV(User user) {
097                    StringBundler sb = new StringBundler(
098                            PropsValues.USERS_EXPORT_CSV_FIELDS.length * 2);
099    
100                    for (int i = 0; i < PropsValues.USERS_EXPORT_CSV_FIELDS.length; i++) {
101                            String field = PropsValues.USERS_EXPORT_CSV_FIELDS[i];
102    
103                            if (field.equals("fullName")) {
104                                    sb.append(CSVUtil.encode(user.getFullName()));
105                            }
106                            else if (field.startsWith("expando:")) {
107                                    String attributeName = field.substring(8);
108    
109                                    ExpandoBridge expandoBridge = user.getExpandoBridge();
110    
111                                    sb.append(
112                                            CSVUtil.encode(expandoBridge.getAttribute(attributeName)));
113                            }
114                            else {
115                                    sb.append(
116                                            CSVUtil.encode(BeanPropertiesUtil.getString(user, field)));
117                            }
118    
119                            if ((i + 1) < PropsValues.USERS_EXPORT_CSV_FIELDS.length) {
120                                    sb.append(StringPool.COMMA);
121                            }
122                    }
123    
124                    sb.append(StringPool.NEW_LINE);
125    
126                    return sb.toString();
127            }
128    
129            protected List<User> getUsers(
130                            ActionRequest actionRequest, ActionResponse actionResponse,
131                            ThemeDisplay themeDisplay)
132                    throws Exception {
133    
134                    PortletURL portletURL =
135                            ((ActionResponseImpl)actionResponse).createRenderURL(
136                                    PortletKeys.USERS_ADMIN);
137    
138                    UserSearch userSearch = new UserSearch(actionRequest, portletURL);
139    
140                    UserSearchTerms searchTerms =
141                            (UserSearchTerms)userSearch.getSearchTerms();
142    
143                    searchTerms.setStatus(WorkflowConstants.STATUS_APPROVED);
144    
145                    LinkedHashMap<String, Object> params =
146                            new LinkedHashMap<String, Object>();
147    
148                    long organizationId = searchTerms.getOrganizationId();
149    
150                    if (organizationId > 0) {
151                            params.put("usersOrgs", new Long(organizationId));
152                    }
153    
154                    long roleId = searchTerms.getRoleId();
155    
156                    if (roleId > 0) {
157                            params.put("usersRoles", new Long(roleId));
158                    }
159    
160                    long userGroupId = searchTerms.getUserGroupId();
161    
162                    if (userGroupId > 0) {
163                            params.put("usersUserGroups", new Long(userGroupId));
164                    }
165    
166                    if (searchTerms.isAdvancedSearch()) {
167                            return UserLocalServiceUtil.search(
168                                    themeDisplay.getCompanyId(), searchTerms.getFirstName(),
169                                    searchTerms.getMiddleName(), searchTerms.getLastName(),
170                                    searchTerms.getScreenName(), searchTerms.getEmailAddress(),
171                                    searchTerms.getStatus(), params, searchTerms.isAndOperator(),
172                                    QueryUtil.ALL_POS, QueryUtil.ALL_POS, (OrderByComparator)null);
173                    }
174                    else {
175                            return UserLocalServiceUtil.search(
176                                    themeDisplay.getCompanyId(), searchTerms.getKeywords(),
177                                    searchTerms.getStatus(), params, QueryUtil.ALL_POS,
178                                    QueryUtil.ALL_POS, (OrderByComparator)null);
179                    }
180            }
181    
182            protected String getUsersCSV(
183                            ActionRequest actionRequest, ActionResponse actionResponse)
184                    throws Exception {
185    
186                    ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(
187                            WebKeys.THEME_DISPLAY);
188    
189                    PermissionChecker permissionChecker =
190                            themeDisplay.getPermissionChecker();
191    
192                    if (!PortalPermissionUtil.contains(
193                                    permissionChecker, ActionKeys.EXPORT_USER)) {
194    
195                            return StringPool.BLANK;
196                    }
197    
198                    String exportProgressId = ParamUtil.getString(
199                            actionRequest, "exportProgressId");
200    
201                    ProgressTracker progressTracker = new ProgressTracker(
202                            actionRequest, exportProgressId);
203    
204                    progressTracker.start();
205    
206                    List<User> users = getUsers(
207                            actionRequest, actionResponse, themeDisplay);
208    
209                    int percentage = 10;
210                    int total = users.size();
211    
212                    progressTracker.updateProgress(percentage);
213    
214                    if (total == 0) {
215                            return StringPool.BLANK;
216                    }
217    
218                    StringBundler sb = new StringBundler(users.size() * 4);
219    
220                    Iterator<User> itr = users.iterator();
221    
222                    for (int i = 0; itr.hasNext(); i++) {
223                            User user = itr.next();
224    
225                            sb.append(getUserCSV(user));
226    
227                            percentage = Math.min(10 + (i * 90) / total, 99);
228    
229                            progressTracker.updateProgress(percentage);
230                    }
231    
232                    progressTracker.finish();
233    
234                    return sb.toString();
235            }
236    
237    }