1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| package sncfinfogerance.server;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class FileServlet extends HttpServlet {
private static final int DEFAULT_BUFFER_SIZE = 10240;
private String filePath = null;
private String xmlFile = null;
public void init() throws ServletException {
//un fois deployé, ca me devrai le repertoire d'install de tomcat
this.setFilePath(System.getProperty("user.dir"));
InfogeranceRemoteServiceImpl.getLogError().info(this.getFilePath());
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String requestedFile = request.getPathInfo();
this.setXmlFile(request.getParameter("file"));
if (requestedFile == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
File file = new File(this.getFilePath(), this.getXmlFile());
if (!file.exists()) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
String contentType = getServletContext().getMimeType(file.getName());
if (contentType == null) {
contentType = "application/octet-stream";
}
response.reset();
response.setBufferSize(DEFAULT_BUFFER_SIZE);
response.setContentType(contentType);
response.setContentLength((int)file.length());
response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
} finally {
close(output);
close(input);
}
}
private static void close(Closeable resource) {
if (resource != null) {
try {
resource.close();
} catch (IOException ioe) {
InfogeranceRemoteServiceImpl.getLogError().severe("FileServlet: Close: " + resource.toString() + " ,\n" + ioe.toString());
}
}
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public String getXmlFile() {
return xmlFile;
}
public void setXmlFile(String xmlFile) {
this.xmlFile = xmlFile;
}
} |
Partager