/*
Dateiverwaltung - File management in your browser
Copyright (C) 2017 Ulrich Hilger, http://uhilger.de
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see .
*/
package de.uhilger.filecms.web;
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.data.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());
private String targetDirStr;
/**
* 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();
FileItem fileItem = null;
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());
fileItem = item;
}
}
File targetDir = getTargetDir(request, targetDirStr);
if(targetDir != null && fileItem != null) {
logger.log(Level.FINER, "targetDir before upload: " + targetDir.getAbsolutePath());
processUploadedFile(targetDir, fileItem, 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) {
File targetDir = null;
if(relPath != null) {
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);
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 String) {
String baseStr = (String) o;
logger.fine(baseStr);
File file = new File(baseStr);
base = new FileRef(file.getAbsolutePath(), file.isDirectory());
}
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) {
File uploadedFile = new File(targetDir, fileName);
uploadedFile.getParentFile().mkdirs();
logger.log(Level.FINER, "writeToFile " + uploadedFile.getAbsolutePath());
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.FINER, "field name: " + name + ", value: " + value);
//...
if(name.equals("pfad")) {
targetDirStr = 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;
}//
}