use of org.apache.commons.fileupload.FileItemFactory in project webprotege by protegeproject.
the class FileUploadServlet method doPost.
@Override
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
WebProtegeSession webProtegeSession = new WebProtegeSessionImpl(req.getSession());
UserId userId = webProtegeSession.getUserInSession();
if (!accessManager.hasPermission(Subject.forUser(userId), ApplicationResource.get(), BuiltInAction.UPLOAD_PROJECT)) {
sendErrorMessage(resp, "You do not have permission to upload files to " + applicationNameSupplier.get());
}
logger.info("Received upload request from {} at {}", webProtegeSession.getUserInSession(), formatAddr(req));
resp.setHeader("Content-Type", RESPONSE_MIME_TYPE);
try {
if (ServletFileUpload.isMultipartContent(req)) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(maxUploadSizeSupplier.get());
List<FileItem> items = upload.parseRequest(req);
for (FileItem item : items) {
if (!item.isFormField()) {
File uploadedFile = createServerSideFile();
item.write(uploadedFile);
long sizeInBytes = uploadedFile.length();
long computedFileSizeInBytes = computeFileSize(uploadedFile);
logger.info("File size is {} bytes. Computed file size is {} bytes.", sizeInBytes, computedFileSizeInBytes);
if (computedFileSizeInBytes > maxUploadSizeSupplier.get()) {
sendFileSizeTooLargeResponse(resp);
} else {
logger.info("Stored uploaded file with name {}", uploadedFile.getName());
resp.setStatus(HttpServletResponse.SC_CREATED);
sendSuccessMessage(resp, uploadedFile.getName());
}
return;
}
}
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not find form file item");
} else {
logger.info("Bad upload request: POST must be multipart encoding.");
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "POST must be multipart encoding.");
}
} catch (FileUploadBase.FileSizeLimitExceededException | FileUploadBase.SizeLimitExceededException e) {
sendFileSizeTooLargeResponse(resp);
} catch (FileUploadBase.FileUploadIOException | FileUploadBase.IOFileUploadException e) {
logger.info("File upload failed because an IOException occurred: {}", e.getMessage(), e);
sendErrorMessage(resp, "File upload failed because of an IOException");
} catch (FileUploadBase.InvalidContentTypeException e) {
logger.info("File upload failed because the content type was invalid: {}", e.getMessage());
sendErrorMessage(resp, "File upload failed because the content type is invalid");
} catch (FileUploadException e) {
logger.info("File upload failed: {}", e.getMessage());
sendErrorMessage(resp, "File upload failed");
} catch (Exception e) {
logger.info("File upload failed because of an error when trying to write the file item: {}", e.getMessage(), e);
sendErrorMessage(resp, "File upload failed");
}
}
use of org.apache.commons.fileupload.FileItemFactory in project cerberus-source by cerberustesting.
the class CreateApplicationObject method processRequest.
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* 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
* @throws CerberusException
* @throws JSONException
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, CerberusException, JSONException {
JSONObject jsonResponse = new JSONObject();
Answer ans = new Answer();
MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
ans.setResultMessage(msg);
PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
String charset = request.getCharacterEncoding();
response.setContentType("application/json");
// Calling Servlet Transversal Util.
ServletUtil.servletStart(request);
Map<String, String> fileData = new HashMap<String, String>();
FileItem file = null;
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> fields = upload.parseRequest(request);
Iterator<FileItem> it = fields.iterator();
if (!it.hasNext()) {
return;
}
while (it.hasNext()) {
FileItem fileItem = it.next();
boolean isFormField = fileItem.isFormField();
if (isFormField) {
fileData.put(fileItem.getFieldName(), fileItem.getString("UTF-8"));
} else {
file = fileItem;
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
/**
* Parsing and securing all required parameters.
*/
// Parameter that are already controled by GUI (no need to decode) --> We SECURE them
// Parameter that needs to be secured --> We SECURE+DECODE them
String application = ParameterParserUtil.parseStringParamAndDecode(fileData.get("application"), null, charset);
String object = ParameterParserUtil.parseStringParamAndDecode(fileData.get("object"), null, charset);
String value = ParameterParserUtil.parseStringParam(fileData.get("value"), null);
String usrcreated = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getRemoteUser(), "", charset);
String datecreated = new Timestamp(new java.util.Date().getTime()).toString();
String usrmodif = ParameterParserUtil.parseStringParamAndDecodeAndSanitize(request.getRemoteUser(), "", charset);
String datemodif = new Timestamp(new java.util.Date().getTime()).toString();
/**
* Checking all constrains before calling the services.
*/
if (StringUtil.isNullOrEmpty(application)) {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", "ApplicationObject").replace("%OPERATION%", "Create").replace("%REASON%", "Application name is missing!"));
ans.setResultMessage(msg);
} else if (StringUtil.isNullOrEmpty(object)) {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", "ApplicationObject").replace("%OPERATION%", "Create").replace("%REASON%", "Object name is missing!"));
ans.setResultMessage(msg);
} else {
/**
* All data seems cleans so we can call the services.
*/
ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
IApplicationObjectService applicationobjectService = appContext.getBean(IApplicationObjectService.class);
IFactoryApplicationObject factoryApplicationobject = appContext.getBean(IFactoryApplicationObject.class);
String fileName = "";
if (file != null) {
fileName = file.getName();
}
ApplicationObject applicationData = factoryApplicationobject.create(-1, application, object, value, fileName, usrcreated, datecreated, usrmodif, datemodif);
ans = applicationobjectService.create(applicationData);
if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
/**
* Object created. Adding Log entry.
*/
ILogEventService logEventService = appContext.getBean(LogEventService.class);
logEventService.createForPrivateCalls("/CreateApplicationObject", "CREATE", "Create Application Object: ['" + application + "','" + object + "']", request);
if (file != null) {
AnswerItem an = applicationobjectService.readByKey(application, object);
if (an.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode()) && an.getItem() != null) {
applicationData = (ApplicationObject) an.getItem();
ans = applicationobjectService.uploadFile(applicationData.getID(), file);
if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
}
}
}
}
}
/**
* Formating and returning the json result.
*/
jsonResponse.put("messageType", ans.getResultMessage().getMessage().getCodeString());
jsonResponse.put("message", ans.getResultMessage().getDescription());
response.getWriter().print(jsonResponse);
response.getWriter().flush();
}
use of org.apache.commons.fileupload.FileItemFactory in project cerberus-source by cerberustesting.
the class importFile method doPost.
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (ServletFileUpload.isMultipartContent(request)) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator iterator = items.iterator();
File uploadedFile = null;
String test = "";
String testcase = "";
String step = "";
String load = "";
while (iterator.hasNext()) {
FileItem item = (FileItem) iterator.next();
if (!item.isFormField()) {
String fileName = item.getName();
String root = getServletContext().getRealPath("/");
File pathFile = new File(root + "/cerberusFiles");
if (!pathFile.exists()) {
// boolean status = pathFile.mkdirs();
pathFile.mkdirs();
}
uploadedFile = new File(pathFile + File.separator + fileName);
LOG.debug(uploadedFile.getAbsolutePath());
item.write(uploadedFile);
} else {
String name = item.getFieldName();
if (name.equals("Test")) {
test = item.getString();
} else if (name.equals("Testcase")) {
testcase = item.getString();
} else if (name.equals("Step")) {
step = item.getString();
} else if (name.equals("Load")) {
load = item.getString();
}
}
}
response.sendRedirect("ImportHTML.jsp?Test=" + test + "&Testcase=" + testcase + "&Step=" + step + "&Load=" + load + "&FilePath=" + uploadedFile.getAbsolutePath());
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
use of org.apache.commons.fileupload.FileItemFactory in project cerberus-source by cerberustesting.
the class CreateTestDataLib method processRequest.
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* 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 {
ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
IFactoryTestDataLibData tdldFactory = appContext.getBean(IFactoryTestDataLibData.class);
ITestDataLibDataService tdldService = appContext.getBean(ITestDataLibDataService.class);
IParameterService parameterService = appContext.getBean(IParameterService.class);
JSONObject jsonResponse = new JSONObject();
Answer ans = new Answer();
AnswerItem ansItem = new AnswerItem();
MessageEvent msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_UNEXPECTED);
msg.setDescription(msg.getDescription().replace("%DESCRIPTION%", ""));
ans.setResultMessage(msg);
PolicyFactory policy = Sanitizers.FORMATTING.and(Sanitizers.LINKS);
String charset = request.getCharacterEncoding();
response.setContentType("application/json");
Map<String, String> fileData = new HashMap<String, String>();
FileItem file = null;
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> fields = upload.parseRequest(request);
Iterator<FileItem> it = fields.iterator();
if (!it.hasNext()) {
return;
}
while (it.hasNext()) {
FileItem fileItem = it.next();
boolean isFormField = fileItem.isFormField();
if (isFormField) {
fileData.put(fileItem.getFieldName(), ParameterParserUtil.parseStringParamAndDecode(fileItem.getString("UTF-8"), "", charset));
} else {
file = fileItem;
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
try {
/**
* Parsing and securing all required parameters.
*/
// Parameter that are already controled by GUI (no need to decode) --> We SECURE them
String type = policy.sanitize(fileData.get("type"));
String system = policy.sanitize(fileData.get("system"));
String environment = policy.sanitize(fileData.get("environment"));
String country = policy.sanitize(fileData.get("country"));
String database = policy.sanitize(fileData.get("database"));
String databaseUrl = policy.sanitize(fileData.get("databaseUrl"));
String databaseCsv = policy.sanitize(fileData.get("databaseCsv"));
// Parameter that needs to be secured --> We SECURE+DECODE them
// this is mandatory
String name = fileData.get("name");
String group = fileData.get("group");
String description = fileData.get("libdescription");
String service = fileData.get("service");
// Parameter that we cannot secure as we need the html --> We DECODE them
String script = fileData.get("script");
String servicePath = fileData.get("servicepath");
String method = fileData.get("method");
String envelope = fileData.get("envelope");
String csvUrl = fileData.get("csvUrl");
String separator = fileData.get("separator");
String test = fileData.get("subdataCheck");
/**
* Checking all constrains before calling the services.
*/
// Prepare the final answer.
MessageEvent msg1 = new MessageEvent(MessageEventEnum.GENERIC_OK);
Answer finalAnswer = new Answer(msg1);
if (StringUtil.isNullOrEmpty(name)) {
msg = new MessageEvent(MessageEventEnum.DATA_OPERATION_ERROR_EXPECTED);
msg.setDescription(msg.getDescription().replace("%ITEM%", "Test Data Library").replace("%OPERATION%", "Create").replace("%REASON%", "Test data library name is missing! "));
finalAnswer.setResultMessage(msg);
} else {
/**
* All data seems cleans so we can call the services.
*/
ITestDataLibService libService = appContext.getBean(ITestDataLibService.class);
IFactoryTestDataLib factoryLibService = appContext.getBean(IFactoryTestDataLib.class);
TestDataLib lib = factoryLibService.create(0, name, system, environment, country, group, type, database, script, databaseUrl, service, servicePath, method, envelope, databaseCsv, csvUrl, separator, description, request.getRemoteUser(), null, "", null, null, null, null, null);
// Creates the entries and the subdata list
ansItem = libService.create(lib);
finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ansItem);
/**
* Object created. Adding Log entry.
*/
if (ansItem.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
ILogEventService logEventService = appContext.getBean(LogEventService.class);
logEventService.createForPrivateCalls("/CreateTestDataLib", "CREATE", "Create TestDataLib : " + request.getParameter("name"), request);
}
List<TestDataLibData> tdldList = new ArrayList();
TestDataLib dataLibWithUploadedFile = (TestDataLib) ansItem.getItem();
if (file != null) {
ans = libService.uploadFile(dataLibWithUploadedFile.getTestDataLibID(), file);
if (ans.isCodeEquals(MessageEventEnum.DATA_OPERATION_OK.getCode())) {
dataLibWithUploadedFile.setCsvUrl(File.separator + dataLibWithUploadedFile.getTestDataLibID() + File.separator + file.getName());
libService.update(dataLibWithUploadedFile);
}
}
// Getting list of SubData from JSON Call
if (fileData.get("subDataList") != null) {
JSONArray objSubDataArray = new JSONArray(fileData.get("subDataList"));
tdldList = getSubDataFromParameter(request, appContext, dataLibWithUploadedFile.getTestDataLibID(), objSubDataArray);
}
if (file != null && test.equals("1")) {
String firstLine = "";
String secondLine = "";
try (BufferedReader reader = new BufferedReader(new FileReader(parameterService.getParameterStringByKey("cerberus_testdatalibCSV_path", "", null) + lib.getCsvUrl()))) {
firstLine = reader.readLine();
secondLine = reader.readLine();
String[] firstLineSubData = (!dataLibWithUploadedFile.getSeparator().isEmpty()) ? firstLine.split(dataLibWithUploadedFile.getSeparator()) : firstLine.split(",");
String[] secondLineSubData = (!dataLibWithUploadedFile.getSeparator().isEmpty()) ? secondLine.split(dataLibWithUploadedFile.getSeparator()) : secondLine.split(",");
int i = 0;
int y = 1;
TestDataLibData firstLineLibData = tdldList.get(0);
tdldList = new ArrayList();
if (StringUtil.isNullOrEmpty(firstLineLibData.getColumnPosition())) {
firstLineLibData.setColumnPosition("1");
}
if (StringUtil.isNullOrEmpty(firstLineLibData.getValue())) {
firstLineLibData.setValue(secondLineSubData[0]);
}
if (StringUtil.isNullOrEmpty(firstLineLibData.getColumn())) {
firstLineLibData.setColumn(firstLineSubData[0]);
}
tdldList.add(firstLineLibData);
for (String item : firstLineSubData) {
TestDataLibData tdld = tdldFactory.create(null, dataLibWithUploadedFile.getTestDataLibID(), item + "_" + y, secondLineSubData[i], item, null, Integer.toString(y), null);
tdldList.add(tdld);
i++;
y++;
}
// Update the Database with the new list.
} finally {
try {
file.getInputStream().close();
} catch (Throwable ignore) {
}
}
}
ans = tdldService.compareListAndUpdateInsertDeleteElements(dataLibWithUploadedFile.getTestDataLibID(), tdldList);
finalAnswer = AnswerUtil.agregateAnswer(finalAnswer, (Answer) ans);
}
/**
* Formating and returning the json result.
*/
// sets the message returned by the operations
jsonResponse.put("messageType", finalAnswer.getResultMessage().getMessage().getCodeString());
jsonResponse.put("message", finalAnswer.getResultMessage().getDescription());
response.getWriter().print(jsonResponse);
response.getWriter().flush();
} catch (JSONException ex) {
LOG.warn(ex);
response.getWriter().print(AnswerUtil.createGenericErrorAnswer());
response.getWriter().flush();
}
}
use of org.apache.commons.fileupload.FileItemFactory in project mica2 by obiba.
the class TempFilesResource method getUploadedFile.
FileItem getUploadedFile(HttpServletRequest request) throws FileUploadException {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
for (FileItem fileItem : upload.parseRequest(request)) {
if (!fileItem.isFormField()) {
return fileItem;
}
}
return null;
}
Aggregations