Softwareprojektmanagement/src/main/java/de/hsel/spm/baudas/web/UploadServlet.java

121 lines
3.4 KiB
Java

package de.hsel.spm.baudas.web;
import de.hsel.spm.baudas.BauDas;
import org.jetbrains.annotations.NotNull;
import weka.core.converters.CSVLoader;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
/**
* saves uploaded files.
*
* @author Johannes Theiner, Julian Hinxlage
* @version 0.1
* @since 0.1
**/
@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 14144111845151L;
/**
* let weka check if the format is valid.
*
* @param stream input stream
* @return format valid
*/
private boolean checkFormat(InputStream stream) {
CSVLoader loader = new CSVLoader();
try {
loader.setSource(stream);
return loader.getDataSet() != null;
} catch (Exception e) {
return false;
}
}
/**
* validates file and saves it.
*
* @param req request object
* @param resp response object
* @throws IOException failed to initialize print writer
*/
@Override
protected void doPost(@NotNull HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding(StandardCharsets.UTF_8.name());
Part filePart = req.getPart("file");
if (filePart == null) {
error(resp, ErrorCode.FILE_NOT_FOUND);
return;
}
if (filePart.getSubmittedFileName() == null) {
error(resp, ErrorCode.FILE_NOT_FOUND);
return;
}
String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
if (fileName == null) {
error(resp, ErrorCode.FILE_NOT_FOUND);
return;
}
InputStream inputStream = filePart.getInputStream();
if (inputStream == null) {
error(resp, ErrorCode.FILE_NOT_FOUND);
return;
}
if (inputStream.available() == 0) {
error(resp, ErrorCode.EMPTY_FILE);
return;
}
if (!checkFormat(inputStream)) {
error(resp, ErrorCode.INVALID_FORMAT);
return;
} else {
inputStream = filePart.getInputStream();
}
Path path = DatasetManagement.add(fileName, req.getSession().getId());
if (!path.toFile().exists()) {
Files.createFile(path);
}
Files.copy(inputStream, path, StandardCopyOption.REPLACE_EXISTING);
}
/**
* redirect to error page.
*
* @param response response object
* @param code error code
*/
private void error(@NotNull HttpServletResponse response, @NotNull ErrorCode code) {
try {
response.sendRedirect("error.jsp?code=" + code);
} catch (IOException e) {
BauDas.getLogger().throwing(this.getClass().getName(), this.getClass().getEnclosingMethod().getName(), e);
}
}
}