01: // Copyright (C) 2003,2004,2005 by Object Mentor, Inc. All rights reserved.
02: // Released under the terms of the GNU General Public License version 2 or later.
03: package fitnesse.responders.files;
04:
05: import fitnesse.*;
06: import fitnesse.responders.SecureResponder;
07: import fitnesse.util.FileUtil;
08: import fitnesse.authentication.*;
09: import fitnesse.http.*;
10: import java.io.*;
11: import java.util.regex.*;
12:
13: public class UploadResponder implements SecureResponder {
14: private static final Pattern filenamePattern = Pattern
15: .compile("([^/\\\\]*[/\\\\])*([^/\\\\]*)");
16:
17: private String rootPath;
18:
19: public Response makeResponse(FitNesseContext context,
20: Request request) throws Exception {
21: rootPath = context.rootPagePath;
22: SimpleResponse response = new SimpleResponse();
23: String resource = request.getResource();
24: UploadedFile uploadedFile = (UploadedFile) request
25: .getInput("file");
26: if (uploadedFile.isUsable()) {
27: File file = makeFileToCreate(uploadedFile, resource);
28: writeFile(file, uploadedFile);
29: }
30:
31: response.redirect("/" + resource);
32: return response;
33: }
34:
35: public void writeFile(File file, UploadedFile uploadedFile)
36: throws Exception {
37: boolean renamed = uploadedFile.getFile().renameTo(file);
38: if (!renamed) {
39: InputStream input = new BufferedInputStream(
40: new FileInputStream(uploadedFile.getFile()));
41: OutputStream output = new BufferedOutputStream(
42: new FileOutputStream(file));
43: FileUtil.copyBytes(input, output);
44: input.close();
45: output.close();
46: uploadedFile.delete();
47: }
48: }
49:
50: private File makeFileToCreate(UploadedFile uploadedFile,
51: String resource) {
52: String relativeFilename = makeRelativeFilename(uploadedFile
53: .getName());
54: String filename = relativeFilename;
55: int prefix = 1;
56: File file = new File(makeFullFilename(resource, filename));
57: while (file.exists()) {
58: filename = makeNewFilename(relativeFilename, prefix++);
59: file = new File(makeFullFilename(resource, filename));
60: }
61: return file;
62: }
63:
64: private String makeFullFilename(String resource, String filename) {
65: return rootPath + "/" + resource + filename;
66: }
67:
68: public static String makeRelativeFilename(String name) {
69: Matcher match = filenamePattern.matcher(name);
70: if (match.find())
71: return match.group(2);
72: else
73: return name;
74: }
75:
76: public static String makeNewFilename(String filename, int copyId) {
77: String[] parts = filename.split("\\.");
78:
79: if (parts.length == 1)
80: return filename + "_copy" + copyId;
81: else {
82: String newName = "";
83: for (int i = 0; i < parts.length - 1; i++) {
84: if (i != 0)
85: newName += ".";
86: newName += parts[i];
87: }
88: newName += "_copy" + copyId + "." + parts[parts.length - 1];
89: return newName;
90: }
91: }
92:
93: public SecureOperation getSecureOperation() {
94: return new AlwaysSecureOperation();
95: }
96: }
|