1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * This library is free software; you can redistribute it and/or modify it under
5    * the terms of the GNU Lesser General Public License as published by the Free
6    * Software Foundation; either version 2.1 of the License, or (at your option)
7    * any later version.
8    *
9    * This library is distributed in the hope that it will be useful, but WITHOUT
10   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11   * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
12   * details.
13   */
14  
15  package com.liferay.portlet.enterpriseadmin.action;
16  
17  import com.liferay.portal.kernel.dao.orm.QueryUtil;
18  import com.liferay.portal.kernel.json.JSONObject;
19  import com.liferay.portal.kernel.servlet.SessionErrors;
20  import com.liferay.portal.kernel.util.ContentTypes;
21  import com.liferay.portal.kernel.util.OrderByComparator;
22  import com.liferay.portal.kernel.util.ParamUtil;
23  import com.liferay.portal.kernel.util.ProgressTracker;
24  import com.liferay.portal.kernel.util.StringBundler;
25  import com.liferay.portal.kernel.util.StringPool;
26  import com.liferay.portal.model.User;
27  import com.liferay.portal.security.permission.ActionKeys;
28  import com.liferay.portal.security.permission.PermissionChecker;
29  import com.liferay.portal.service.UserLocalServiceUtil;
30  import com.liferay.portal.service.http.UserJSONSerializer;
31  import com.liferay.portal.service.permission.PortalPermissionUtil;
32  import com.liferay.portal.struts.ActionConstants;
33  import com.liferay.portal.struts.PortletAction;
34  import com.liferay.portal.theme.ThemeDisplay;
35  import com.liferay.portal.util.PortalUtil;
36  import com.liferay.portal.util.PortletKeys;
37  import com.liferay.portal.util.PropsValues;
38  import com.liferay.portal.util.WebKeys;
39  import com.liferay.portlet.ActionResponseImpl;
40  import com.liferay.portlet.enterpriseadmin.search.UserSearch;
41  import com.liferay.portlet.enterpriseadmin.search.UserSearchTerms;
42  import com.liferay.portlet.expando.model.ExpandoBridge;
43  import com.liferay.util.servlet.ServletResponseUtil;
44  
45  import java.util.Iterator;
46  import java.util.LinkedHashMap;
47  import java.util.List;
48  
49  import javax.portlet.ActionRequest;
50  import javax.portlet.ActionResponse;
51  import javax.portlet.PortletConfig;
52  import javax.portlet.PortletURL;
53  
54  import javax.servlet.http.HttpServletRequest;
55  import javax.servlet.http.HttpServletResponse;
56  
57  import org.apache.struts.action.ActionForm;
58  import org.apache.struts.action.ActionMapping;
59  
60  /**
61   * <a href="ExportUsersAction.java.html"><b><i>View Source</i></b></a>
62   *
63   * @author Brian Wing Shun Chan
64   * @author Mika Koivisto
65   */
66  public class ExportUsersAction extends PortletAction {
67  
68      public void processAction(
69              ActionMapping mapping, ActionForm form, PortletConfig portletConfig,
70              ActionRequest actionRequest, ActionResponse actionResponse)
71          throws Exception {
72  
73          try {
74              String csv = getUsersCSV(actionRequest, actionResponse);
75  
76              String fileName = "users.csv";
77              byte[] bytes = csv.getBytes();
78  
79              HttpServletRequest request = PortalUtil.getHttpServletRequest(
80                  actionRequest);
81              HttpServletResponse response = PortalUtil.getHttpServletResponse(
82                  actionResponse);
83  
84              ServletResponseUtil.sendFile(
85                  request, response, fileName, bytes, ContentTypes.TEXT_CSV_UTF8);
86  
87              setForward(actionRequest, ActionConstants.COMMON_NULL);
88          }
89          catch (Exception e) {
90              SessionErrors.add(actionRequest, e.getClass().getName());
91  
92              setForward(actionRequest, "portlet.enterprise_admin.error");
93          }
94      }
95  
96      protected String getUserCSV(User user) {
97          StringBundler sb = new StringBundler(
98              PropsValues.USERS_EXPORT_CSV_FIELDS.length * 2);
99  
100         JSONObject jsonObject = UserJSONSerializer.toJSONObject(user);
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(user.getFullName());
107             }
108             else if (field.startsWith("expando:")) {
109                 String attributeName = field.substring(7);
110 
111                 ExpandoBridge expandoBridge = user.getExpandoBridge();
112 
113                 sb.append(expandoBridge.getAttribute(attributeName));
114             }
115             else {
116                 sb.append(jsonObject.getString(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.ENTERPRISE_ADMIN_USERS);
137 
138         UserSearch userSearch = new UserSearch(actionRequest, portletURL);
139 
140         UserSearchTerms searchTerms =
141             (UserSearchTerms)userSearch.getSearchTerms();
142 
143         if (!searchTerms.isAdvancedSearch() && !searchTerms.hasActive()) {
144             searchTerms.setActive(Boolean.TRUE);
145         }
146 
147         LinkedHashMap<String, Object> params =
148             new LinkedHashMap<String, Object>();
149 
150         long organizationId = searchTerms.getOrganizationId();
151 
152         if (organizationId > 0) {
153             params.put("usersOrgs", new Long(organizationId));
154         }
155 
156         long roleId = searchTerms.getRoleId();
157 
158         if (roleId > 0) {
159             params.put("usersRoles", new Long(roleId));
160         }
161 
162         long userGroupId = searchTerms.getUserGroupId();
163 
164         if (userGroupId > 0) {
165             params.put("usersUserGroups", new Long(userGroupId));
166         }
167 
168         if (searchTerms.isAdvancedSearch()) {
169             return UserLocalServiceUtil.search(
170                 themeDisplay.getCompanyId(), searchTerms.getFirstName(),
171                 searchTerms.getMiddleName(), searchTerms.getLastName(),
172                 searchTerms.getScreenName(), searchTerms.getEmailAddress(),
173                 searchTerms.getActive(), params, searchTerms.isAndOperator(),
174                 QueryUtil.ALL_POS, QueryUtil.ALL_POS, (OrderByComparator)null);
175         }
176         else {
177             return UserLocalServiceUtil.search(
178                 themeDisplay.getCompanyId(), searchTerms.getKeywords(),
179                 searchTerms.getActive(), params, QueryUtil.ALL_POS,
180                 QueryUtil.ALL_POS, (OrderByComparator)null);
181         }
182     }
183 
184     protected String getUsersCSV(
185             ActionRequest actionRequest, ActionResponse actionResponse)
186         throws Exception {
187 
188         ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(
189             WebKeys.THEME_DISPLAY);
190 
191         PermissionChecker permissionChecker =
192             themeDisplay.getPermissionChecker();
193 
194         if (!PortalPermissionUtil.contains(
195                 permissionChecker, ActionKeys.EXPORT_USER)) {
196 
197             return StringPool.BLANK;
198         }
199 
200         String exportProgressId = ParamUtil.getString(
201             actionRequest, "exportProgressId");
202 
203         ProgressTracker progressTracker = new ProgressTracker(
204             actionRequest, exportProgressId);
205 
206         progressTracker.start();
207 
208         List<User> users = getUsers(
209             actionRequest, actionResponse, themeDisplay);
210 
211         int percentage = 10;
212         int total = users.size();
213 
214         progressTracker.updateProgress(percentage);
215 
216         if (total == 0) {
217             return StringPool.BLANK;
218         }
219 
220         StringBundler sb = new StringBundler(users.size() * 4);
221 
222         Iterator<User> itr = users.iterator();
223 
224         for (int i = 0; itr.hasNext(); i++) {
225             User user = itr.next();
226 
227             sb.append(getUserCSV(user));
228 
229             percentage = Math.min(10 + (i * 90) / total, 99);
230 
231             progressTracker.updateProgress(percentage);
232         }
233 
234         progressTracker.finish();
235 
236         return sb.toString();
237     }
238 
239 }