BrightSide Workbench Full Report + Source Code
DocumentsBean.java
Go to the documentation of this file.
1 /*
2  * TurrĂ³ i Cutiller Foundation. License notice.
3  * Copyright (C) 2011 Lluis TurrĂ³ Cutiller <http://www.turro.org/>
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU Affero General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU Affero General Public License for more details.
14  *
15  * You should have received a copy of the GNU Affero General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  */
18 package org.turro.elephant.documents;
19 
20 import java.io.File;
21 import java.io.FileInputStream;
22 import java.io.FileOutputStream;
23 import java.io.IOException;
24 import java.io.UnsupportedEncodingException;
25 import java.util.ArrayList;
26 import java.util.Arrays;
27 import java.util.Collection;
28 import java.util.HashMap;
29 import java.util.HashSet;
30 import java.util.Iterator;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.Properties;
34 import java.util.Set;
35 import java.util.TreeSet;
36 import java.util.logging.Level;
37 import java.util.logging.Logger;
38 import org.apache.commons.fileupload.FileItem;
39 import org.apache.commons.fileupload.FileItemFactory;
40 import org.apache.commons.fileupload.FileUploadException;
41 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
42 import org.apache.commons.fileupload.servlet.ServletFileUpload;
43 import org.jdom.Document;
44 import org.jdom.Element;
45 import org.jdom.JDOMException;
46 import org.jdom.input.SAXBuilder;
47 import org.turro.elephant.context.ElephantContext;
48 import org.turro.elephant.context.IConstructor;
49 import org.turro.elephant.impl.context.ContextFactory;
50 import org.turro.elephant.impl.util.Localizer;
51 import org.turro.elephant.impl.util.ProcessMessages;
52 import org.turro.elephant.security.IUser;
53 import org.turro.i18n.I_;
54 import org.turro.mail.impl.MailPool;
55 import org.turro.mail.impl.MailUser;
56 
61 public class DocumentsBean {
62 
63  public static final String DOCS_CONFIGURATION = "/WEB-INF/elephant/conf/documents.xml";
64  private IConstructor constructor;
65  private String docsRoot;
66  private String selectedUser, selectedInsertion, selectedFolder, selectedId, selectedRoot;
67  private int mode = 1;
68 
70  public DocumentsBean() {
71  }
72 
73  public void setConstructor(IConstructor constructor) {
74  this.constructor = constructor;
75  constructor.setSessionAttribute("xp_down_mime", ElephantContext.getRootWebPath() + "/_internal/system/mime");
76  getMessages().clear();
77  processParameters();
78  }
79 
81  return constructor;
82  }
83 
86  }
87 
89  ArrayList v = new ArrayList();
90  Element config = getConfiguration();
91 
92  if (config != null) {
93  DocumentsRoot userRoot;
94  Iterator it = config.getChildren("root").iterator();
95  Element el;
96  while (it.hasNext()) {
97  userRoot = null;
98  el = (Element) it.next();
99  if (el.getAttribute("role") == null || constructor.isInRole(el.getAttributeValue("role"))) {
100  docsRoot = el.getTextTrim();
101  userRoot = new DocumentsRoot(this, docsRoot, "", el);
102  v.add(userRoot);
103  }
104  }
105  }
106 
107  return (DocumentsRoot[]) v.toArray(new DocumentsRoot[0]);
108  }
109 
111  ArrayList v = new ArrayList();
112  Element config = getConfiguration();
113 
114  if (config != null) {
115  DocumentsRoot userRoot;
116  Iterator it = config.getChildren("root").iterator();
117  Element el;
118  while (it.hasNext()) {
119  userRoot = null;
120  el = (Element) it.next();
121  if (el.getAttribute("role") == null || constructor.isInRole(el.getAttributeValue("role"))) {
122  if ("true".equals(el.getAttributeValue("appendUser"))) {
123  docsRoot = el.getTextTrim();
124  userRoot = new DocumentsRoot(this, docsRoot, "", el);
125  v.add(userRoot);
126  }
127  }
128  }
129  }
130 
131  return (DocumentsRoot[]) v.toArray(new DocumentsRoot[0]);
132  }
133 
135  if (selectedUser == null && constructor.getUser() != null) {
136  selectedUser = constructor.getUser().getId();
137  }
138  ArrayList v = new ArrayList();
139  Element config = getConfiguration();
140 
141  if (config != null) {
142  DocumentsRoot userRoot;
143  Iterator it = config.getChildren("root").iterator();
144  Element el;
145  while (it.hasNext()) {
146  userRoot = null;
147  el = (Element) it.next();
148  if (el.getAttribute("role") == null || constructor.isInRole(el.getAttributeValue("role"))) {
149  docsRoot = el.getTextTrim();
150  if ("true".equals(el.getAttributeValue("appendUser"))) {
151  if (selectedUser != null) {
152  userRoot = new DocumentsRoot(this, docsRoot, "/" + selectedUser, el);
153  v.add(userRoot);
154  }
155  } else {
156  userRoot = new DocumentsRoot(this, docsRoot, "", el);
157  v.add(userRoot);
158  }
159 
160  if (userRoot != null) {
161  String id;
162  for (int i = 0; i < 30; i++) {
163  id = userRoot.readConfig("allowed." + i);
164  if (id != null) {
165  v.add(new DocumentsRoot(this, docsRoot, "/" + id, el));
166  }
167  }
168  }
169  }
170  }
171  }
172 
173  return (DocumentsRoot[]) v.toArray(new DocumentsRoot[0]);
174  }
175 
176  public void setSelectedId(String selectedId) {
177  this.selectedId = selectedId;
178  }
179 
180  public void setSelectedRoot(String selectedRoot) {
181  this.selectedRoot = selectedRoot;
182  }
183 
185  for(DocumentsRoot dr : getDocumentRoots()) {
186  if(selectedId.equals(dr.getAttribute("id"))) {
187  dr.setFileDocumentSelected(selectedRoot);
188  return dr;
189  }
190  }
191  return null;
192  }
193 
195  if (selectedInsertion == null) {
196  return new DocumentsRoot[0];
197  }
198  ArrayList v = new ArrayList();
199  Element config = getConfiguration();
200 
201  if (config != null) {
202  DocumentsRoot userRoot;
203  Iterator it = config.getChildren("root").iterator();
204  Element el;
205  while (it.hasNext()) {
206  userRoot = null;
207  el = (Element) it.next();
208  if (el.getAttribute("role") == null || constructor.isInRole(el.getAttributeValue("role"))) {
209  docsRoot = el.getTextTrim();
210  if ("true".equals(el.getAttributeValue("appendUser"))) {
211  userRoot = new DocumentsRoot(this, docsRoot, "/" + selectedInsertion, el);
212  v.add(userRoot);
213  } else {
214  userRoot = new DocumentsRoot(this, docsRoot, "", el);
215  v.add(userRoot);
216  }
217  }
218  }
219  }
220 
221  return (DocumentsRoot[]) v.toArray(new DocumentsRoot[0]);
222  }
223 
225  ArrayList v = new ArrayList();
226  for (DocumentsRoot dr : getRootsForInsertion()) {
227  fillFolders(v, dr.getFileDocumentRoot(), "true".equals(dr.getAttribute("onlyLeafInsertion")));
228  }
229  FileDocument fds[] = (FileDocument[]) v.toArray(new FileDocument[0]);
230  Arrays.sort(fds);
231  return fds;
232  }
233 
234  public Collection getInsertionFoldersWrapped() {
235  ArrayList v = new ArrayList();
236  for(FileDocument fd : getInsertionFolders()) {
237  v.add(new FileDocumentWrapper(fd, false));
238  }
239  return v;
240  }
241 
242 
244  ArrayList v = new ArrayList();
245  for (DocumentsRoot dr : getRootsForInsertion()) {
246  fillFolders(v, dr.getFileDocumentRoot(), false);
247  }
248  return (FileDocument[]) v.toArray(new FileDocument[0]);
249  }
250 
251  private void fillFolders(ArrayList v, FileDocument root, boolean onlyLeafInsert) {
252  boolean leaf = true;
253  for (FileDocument fd : root.getListFolders()) {
254  if (fd.isDirectory()) {
255  fillFolders(v, fd, onlyLeafInsert);
256  leaf = false;
257  }
258  }
259  if (leaf || !onlyLeafInsert) {
260  v.add(root);
261  }
262  }
263 
265  ArrayList v = new ArrayList();
266  for(DocumentsRoot dr : getRealRoots()) {
267  v.addAll(dr.getNotValidated());
268  }
269  return (FileDocument[]) v.toArray(new FileDocument[0]);
270  }
271 
272  public String getDownloadURL() {
273  return ElephantContext.getRootWebPath() + "/Download";
274  }
275 
277  return constructor.getLocalizer();
278  }
279 
280  public Properties getPropertiesFile(String file) {
281  Properties tmp = new Properties();
282  if (new File(file).exists()) {
283  FileInputStream fis;
284  try {
285  fis = new FileInputStream(file);
286  tmp.load(fis);
287  fis.close();
288  } catch (Exception ex) {
289  Logger.getLogger(DocumentsBean.class.getName()).log(Level.SEVERE, ElephantContext.logMsg(null), ex);
290  }
291  }
292  return tmp;
293  }
294 
295  public void savePropertiesFile(Properties props, String file) {
296  FileOutputStream fos;
297  try {
298  fos = new FileOutputStream(file);
299  props.store(fos, null);
300  fos.close();
301  } catch (Exception ex) {
302  Logger.getLogger(DocumentsBean.class.getName()).log(Level.SEVERE, ElephantContext.logMsg(null), ex);
303  }
304  }
305 
306  public void setAttribute(String key, String value) {
307  constructor.setSessionAttribute(key, value);
308  }
309 
310  public boolean getCanViewAs() {
311  return constructor.isInRole("documents:view-as");
312  }
313 
314  public boolean getCanNew() {
315  return constructor.isInRole("documents:new");
316  }
317 
318  public boolean getCanDelete() {
319  return constructor.isInRole("documents:delete");
320  }
321 
322  public boolean getCanNewFolder() {
323  return constructor.isInRole("documents:new-folder");
324  }
325 
326  public boolean getCanDelFolder() {
327  return constructor.isInRole("documents:del-folder");
328  }
329 
330  public boolean getCanEditPermissions() {
331  return constructor.isInRole("documents:edit-allowed");
332  }
333 
334  public boolean getCanNewInsertPoint() {
335  return constructor.isInRole("documents:new-insertpoint");
336  }
337 
338  public boolean getCanValidate() {
339  return constructor.isInRole("documents:validate");
340  }
341 
342  public boolean getCanContact() {
343  return constructor.isInRole("contact:list");
344  }
345 
346  public Set getUsers() {
347  Set tmp = new TreeSet();
348  for (IUser usr : (List<IUser>) constructor.getUser().getUsers()) {
349  if (usr.isInRole("documents:list")) {
350  tmp.add(new UserWrapper(this, usr));
351  }
352  }
353  return tmp;
354  }
355 
356  public boolean isSelected(IUser user) {
357  if (selectedUser == null && constructor.getUser() != null) {
358  selectedUser = constructor.getUser().getId();
359  }
360 
361  return selectedUser != null && selectedUser.equals(user.getId());
362  }
363 
364  public String getSelectedUser() {
365  return selectedUser;
366  }
367 
368  public Set<DocumentsRoot> getInsertionPointsWrapped() {
369  Set tmp = new TreeSet();
370  Element config = getConfiguration();
371 
372  if (config != null) {
373  DocumentsRoot userRoot;
374  Iterator it = config.getChildren("root").iterator();
375  Element el;
376  while (it.hasNext()) {
377  userRoot = null;
378  el = (Element) it.next();
379  if (el.getAttribute("role") == null || constructor.isInRole(el.getAttributeValue("role"))) {
380  docsRoot = el.getTextTrim();
381  userRoot = new DocumentsRoot(this, docsRoot, "", el);
382  tmp.addAll(userRoot.getInsertionPointsWrapped());
383  }
384  }
385  }
386 
387  return tmp;
388  }
389 
390  public boolean isInsertionSelected(FileDocument fd) {
391  return selectedInsertion != null && selectedInsertion.equals(fd.getName());
392  }
393 
394  public boolean isFolderSelected(FileDocument fd) {
395  return selectedFolder != null && selectedFolder.equals(fd.getAbsolutePath());
396  }
397 
398  public int getMode() {
399  return mode;
400  }
401 
402  public String getShowingUsers() {
403  return mode == 1 ? "checked" : "";
404  }
405 
406  public String getManagingFiles() {
407  return mode == 2 ? "checked" : "";
408  }
409 
410  public String getManagingPermissions() {
411  return mode == 3 ? "checked" : "";
412  }
413 
414  public String getAddingInsertionPoint() {
415  return mode == 4 ? "checked" : "";
416  }
417 
418  public String getValidating() {
419  return mode == 5 ? "checked" : "";
420  }
421 
422  private DocumentsRoot getFromPath(String path) {
423  for(DocumentsRoot dr : getRealRoots()) {
424  if(path.startsWith(dr.getPath())) {
425  return dr;
426  }
427  }
428  return null;
429  }
430 
431  private void processParameters() {
432  if (constructor.isInRole("documents:new") && ServletFileUpload.isMultipartContent(constructor.getRequest())) {
433  try {
434  FileItemFactory factory = new DiskFileItemFactory();
435  ServletFileUpload upload = new ServletFileUpload(factory);
436  upload.setHeaderEncoding(ElephantContext.getEncoding());
437  List items = upload.parseRequest(constructor.getRequest());
438  Iterator iter = items.iterator();
439  FileItem file = null;
440  Map fields = new HashMap();
441  while (iter.hasNext()) {
442  FileItem item = (FileItem) iter.next();
443  if (!item.isFormField()) {
444  file = item;
445  } else {
446  fields.put(item.getFieldName(), item.getString(ElephantContext.getEncoding()));
447  }
448  }
449  if (file != null) {
450  try {
451  String path = (String) fields.get("path");
452  selectedFolder = path;
453  String onlyName = file.getName();
454  int p = onlyName.lastIndexOf('/');
455  if (p == -1) {
456  p = onlyName.lastIndexOf('\\');
457  }
458  new File(path).mkdirs();
459  DocumentsRoot dr = getFromPath(path);
460  boolean mustValidate = dr != null && "true".equals(dr.getAttribute("validate"));
461  String realName = path + "/" + (mustValidate ? "." : "") + onlyName.substring(p + 1);
462  File uploadedFile = new File(realName);
463  file.write(uploadedFile);
464  sendRequiresValidationEmail(dr, uploadedFile);
465  } catch (Exception ex) {
466  Logger.getLogger(DocumentsBean.class.getName()).log(Level.SEVERE, ElephantContext.logMsg(null), ex);
467  }
468  }
469  } catch (FileUploadException ex) {
470  Logger.getLogger(DocumentsBean.class.getName()).log(Level.SEVERE, ElephantContext.logMsg(null), ex);
471  } catch (UnsupportedEncodingException ex) {
472  Logger.getLogger(DocumentsBean.class.getName()).log(Level.SEVERE, ElephantContext.logMsg(null), ex);
473  }
474  } else if (constructor.isInRole("documents:delete") && constructor.getParameter("delfile") != null) {
475  File file = new File(constructor.getParameter("path"));
476  if (file.exists()) {
477  org.amic.util.file.FileUtil.deleteFile(file);
478  }
479  } else if (constructor.isInRole("documents:new-folder") && constructor.getParameter("newfolder") != null) {
480  File file = new File(constructor.getParameter("path"));
481  if (file.exists()) {
482  file = new File(file.getPath() + "/" + constructor.getParameter("folder").replaceAll("[^\\/a-zA-Z0-9\\-\\_\\.]", "_"));
483  file.mkdir();
484  }
485  } else if (constructor.isInRole("documents:edit-allowed") && constructor.getParameter("saveallowed") != null) {
486  IUser user = ContextFactory.getUser(constructor);
487  user.impersonate(selectedUser);
488  if (user != null) {
489  for (DocumentsRoot dr : getRealRoots()) {
490  if ("true".equals(dr.getAttribute("appendUser"))) {
491  Properties props = dr.getPropertiesFromUser(user);
492  for (int i = 0; i < 30; i++) {
493  props.remove("allowed." + i);
494  }
495  int i = 0;
496  for (FileDocument fd : dr.getInsertionFolders()) {
497  if (constructor.getParameter(fd.getName()) != null) {
498  props.put("allowed." + i++, fd.getName());
499  }
500  }
501  dr.savePropertiesToUser(props, user);
502  getMessages().addMessage(I_.get("Permissions saved"));
503  }
504  }
505  }
506  } else if (constructor.isInRole("documents:new-insertpoint") && constructor.getParameter("addpoint") != null) {
507  for (DocumentsRoot dr : getRealRoots()) {
508  if ("true".equals(dr.getAttribute("appendUser")) && dr.getPath().equals(constructor.getParameter("selectedRoot"))) {
509  dr.addInsertionPoint(constructor.getParameter("idpoint"), constructor.getParameter("namepoint"));
510  }
511  }
512  } else if (constructor.isInRole("documents:validate") && constructor.getParameter("validatefile") != null) {
513  File file = new File(constructor.getParameter("path"));
514  if (file.exists()) {
515  file.renameTo(new File(
516  file.getAbsolutePath().substring(0, file.getAbsolutePath().lastIndexOf("/")) +
517  "/" +
518  file.getName().substring(1)));
519  }
520  } else {
521  if (constructor.getParameter("selectedUser") != null) {
522  selectedUser = constructor.getParameter("selectedUser");
523  }
524  if (constructor.getParameter("selectedInsertion") != null) {
525  selectedInsertion = constructor.getParameter("selectedInsertion");
526  }
527  String m = constructor.getParameter("mode");
528  if (m != null) {
529  mode = Integer.valueOf(m);
530  }
531  }
532  }
533 
534  private Element getConfiguration() {
535  Element config = null;
536  File confFile = new File(ElephantContext.getRealPath(DOCS_CONFIGURATION));
537  if (confFile.exists()) {
538  SAXBuilder builder = new SAXBuilder();
539  Document doc;
540  try {
541  doc = builder.build(confFile);
542  config = doc.getRootElement();
543  } catch (IOException ex) {
544  Logger.getLogger(DocumentsBean.class.getName()).log(Level.SEVERE, ElephantContext.logMsg(null), ex);
545  } catch (JDOMException ex) {
546  Logger.getLogger(DocumentsBean.class.getName()).log(Level.SEVERE, ElephantContext.logMsg(null), ex);
547  }
548  }
549  return config;
550  }
551 
552  private void sendRequiresValidationEmail(DocumentsRoot dr, File uploadedFile) {
553  MailPool mp = (MailPool) ContextFactory.getImplementation(constructor, "IMailPool_Documents");
554  mp.setEncoding(ElephantContext.getEncoding());
555  mp.addCssFile(ElephantContext.getRealPath("/_internal/css/mail.css"));
556  String subject = I_.get("{file} requires validation").replaceAll("\\{file\\}", uploadedFile.getName());
557  Set<MailUser> emails = new HashSet<MailUser>();
558  emails.add(new MailUser(constructor, dr.getAttribute("owner"), "#user", subject, ""));
559  for(MailUser mc : emails) {
560  mp.addToPool(null, mc.getEmail(), null, subject, mc.getMessage(""), "text/html");
561  }
562  mp.sendPool();
563  }
564 }
void savePropertiesFile(Properties props, String file)
void setConstructor(IConstructor constructor)
Set< DocumentsRoot > getInsertionPointsWrapped()
boolean isInsertionSelected(FileDocument fd)
void setAttribute(String key, String value)
void setSessionAttribute(String key, Object value)