1 package org.appfuse.webapp.pages;
2
3 import org.apache.commons.fileupload.FileUploadException;
4 import org.apache.tapestry5.ComponentResources;
5 import org.apache.tapestry5.alerts.AlertManager;
6 import org.apache.tapestry5.alerts.Duration;
7 import org.apache.tapestry5.alerts.Severity;
8 import org.apache.tapestry5.annotations.DiscardAfter;
9 import org.apache.tapestry5.annotations.InjectPage;
10 import org.apache.tapestry5.annotations.Log;
11 import org.apache.tapestry5.annotations.Property;
12 import org.apache.tapestry5.ioc.Messages;
13 import org.apache.tapestry5.ioc.annotations.Inject;
14 import org.apache.tapestry5.services.Context;
15 import org.appfuse.Constants;
16 import org.appfuse.webapp.data.FileData;
17 import org.appfuse.webapp.services.SecurityContext;
18 import org.slf4j.Logger;
19
20 import javax.servlet.http.HttpServletRequest;
21 import java.io.File;
22
23
24
25
26
27
28
29
30
31
32 public class FileUpload {
33
34 @Inject
35 private Logger logger;
36
37 @Inject
38 private Messages messages;
39
40 @Inject
41 private HttpServletRequest request;
42
43 @Inject
44 private AlertManager alertManager;
45
46 @Inject
47 private Context context;
48
49 @Inject
50 private SecurityContext securityContext;
51
52 @Inject
53 private ComponentResources resources;
54
55 @InjectPage
56 private FileDisplay fileDisplay;
57
58 @Property
59 private FileData fileData;
60
61
62 @Log
63 void onPrepare() {
64 fileData = new FileData();
65 }
66
67 @Log
68 void onValidate() {
69 if (fileData.getFile() == null) {
70 return;
71 }
72 }
73
74 @Log
75 Object onCancel() {
76 return Home.class;
77 }
78
79 @DiscardAfter
80 Object onSuccess() {
81
82 File uploadPath = buildUploadPath();
83
84 File copied = new File(uploadPath, fileData.getFileName());
85 fileData.write(copied);
86
87
88 String path = uploadPath.getAbsolutePath() + Constants.FILE_SEP + fileData.getFileName();
89 String url =
90 request.getContextPath() + "/resources/" +
91 securityContext.getUsername() + "/" + fileData.getFileName();
92
93
94 fileData.setPath(path);
95 fileData.setUrl(url);
96
97 fileDisplay.setFileData(fileData);
98
99 return fileDisplay;
100 }
101
102
103 Object onUploadException(FileUploadException exception) {
104 logger.error(String.format("Upload exception: %s ", exception.getMessage()));
105 alertManager.alert(Duration.TRANSIENT,
106 Severity.ERROR,
107 messages.get("maxLengthExceeded"));
108 return this;
109 }
110
111
112 private File buildUploadPath() {
113
114
115 String uploadDir = String.format("%s%s%s%s",
116 request.getSession().getServletContext().getRealPath("/resources"),
117 Constants.FILE_SEP,
118 securityContext.getUsername(),
119 Constants.FILE_SEP);
120
121
122
123 File dirPath = new File(uploadDir);
124
125 if (!dirPath.exists()) {
126 dirPath.mkdirs();
127 }
128
129 return dirPath;
130 }
131
132 }