package de.uhilger.filecms.api;
import static de.uhilger.filecms.api.FileMgr.HOME_DIR_NAME;
import static de.uhilger.filecms.api.FileMgr.HOME_DIR_PATH;
import static de.uhilger.filecms.api.FileMgr.PUB_DIR_NAME;
import static de.uhilger.filecms.api.FileMgr.PUB_DIR_PATH;
import de.uhilger.filecms.web.Initialiser;
import de.uhilger.filesystem.FileRef;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.security.Principal;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.FileCleanerCleanup;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileCleaningTracker;
/**
* Objekte der Klasee UploadServlet nehmen eine Datei per HTTP Multipart Request
* entgegen und speichern sie im webapps-Verzeichnis des Servlet-Containers.
*
* Annahme ist, dass das von javax.servlet.context.tempdir bezeichnete
* Verzeichnis auf CATALINA_BASE/work/Catalina/localhost/[context] zeigt. Von
* dort wird dann das webapps-Verzeichnis als CATALINA_BASE/webapps ermittelt.
*/
public class UploadServlet extends HttpServlet {
public static final String DESC = "file-cms uploader";
private static final Logger logger = Logger.getLogger(UploadServlet.class.getName());
/**
* Processes requests for both HTTP GET
and POST
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//logger.log(Level.INFO, "start");
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
//logger.log(Level.INFO, "isMultipart");
try {
ServletContext servletContext = this.getServletConfig().getServletContext();
// Configure a repository (to ensure a secure temp location is used)
File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
// CATALINA_BASE/work/Catalina/localhost/wbx
// Create a factory for disk-based file items
DiskFileItemFactory factory = newDiskFileItemFactory(servletContext, repository);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
List items = upload.parseRequest(request);
// Process the uploaded items
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
if (item.isFormField()) {
processFormField(item);
} else {
//File base = repository.getParentFile().getParentFile().getParentFile().getParentFile();
//File webapps = new File(base, "webapps");
//logger.info(webapps.getAbsolutePath());
File targetDir = getTargetDir(request, PUB_DIR_NAME);
logger.log(Level.FINE, "rufe processUploadedFile");
processUploadedFile(targetDir, item, true);
}
}
} catch (Exception ex) {
logger.log(Level.SEVERE, null, ex);
}
} else {
// kein Upload
}
/*
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
out.println("");
out.println("");
out.println("");
out.println("Servlet UploadServlet");
out.println("");
out.println("");
out.println("Servlet UploadServlet at " + request.getContextPath() + "
");
out.println("");
out.println("");
}
*/
}
private File getTargetDir(HttpServletRequest request, String relPath) {
logger.finer(relPath);
String targetPath = null;
if(relPath.startsWith(PUB_DIR_NAME)) {
targetPath = PUB_DIR_PATH + getUserName(request) + "/" + relPath.substring(PUB_DIR_NAME.length());
} else if(relPath.startsWith(HOME_DIR_NAME)) {
targetPath = HOME_DIR_PATH + getUserName(request) + "/" + relPath.substring(HOME_DIR_NAME.length());
} else {
// kann eigentlich nicht sein..
}
logger.finer(targetPath);
File targetDir = new File(getBase().getAbsolutePath(), targetPath);
return targetDir;
}
private String getUserName(HttpServletRequest request) {
String userName = null;
Object p = request.getUserPrincipal();
if (p instanceof Principal) {
userName = ((Principal) p).getName();
}
return userName;
}
private FileRef getBase() {
FileRef base = null;
Object o = getServletContext().getAttribute(Initialiser.FILE_BASE);
if (o instanceof FileRef) {
base = (FileRef) o;
}
return base;
}
private void processUploadedFile(File targetDir, FileItem item, boolean writeToFile) throws Exception {
//logger.log(Level.INFO, "start");
// Process a file upload
if (!item.isFormField()) {
String fieldName = item.getFieldName();
String fileName = item.getName();
String contentType = item.getContentType();
boolean isInMemory = item.isInMemory();
long sizeInBytes = item.getSize();
// Process a file upload
if (writeToFile) {
//logger.log(Level.INFO, "writeToFile " + fileName);
File uploadedFile = new File(targetDir, fileName);
item.write(uploadedFile);
} else {
InputStream uploadedStream = item.getInputStream();
//...
uploadedStream.close();
}
}
}
private void processFormField(FileItem item) {
//logger.log(Level.INFO, "start");
// Process a regular form field
if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString();
//logger.log(Level.INFO, "field name: " + name + ", value: " + value);
//...
}
}
public static DiskFileItemFactory newDiskFileItemFactory(ServletContext context,
File repository) {
FileCleaningTracker fileCleaningTracker
= FileCleanerCleanup.getFileCleaningTracker(context);
DiskFileItemFactory factory
= new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD,
repository);
factory.setFileCleaningTracker(fileCleaningTracker);
return factory;
}
//
/**
* Handles the HTTP GET
method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP POST
method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return DESC;
}//
}