use of org.apache.commons.fileupload.FileItem in project RESTdoclet by IG-Group.
the class FileUploadServlet method doPost.
/* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*
* This method accepts a jar and extracts to a location specified by the header key RESTDOCLET_DEPLOY
*/
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String deploySubDir = request.getHeader(RESTDOCLET_DEPLOY);
String deployDir = configPath + File.separator + deploySubDir;
File dir = new File(deployDir);
deleteDir(dir);
if (ServletFileUpload.isMultipartContent(request)) {
try {
LOG.info("Upload request to " + deployDir);
List<FileItem> fileItems = new ServletFileUpload(new DiskFileItemFactory(1024 * 1024, dir)).parseRequest(request);
for (FileItem item : fileItems) {
if (item != null) {
LOG.debug(item.getName());
JarInputStream jis = new JarInputStream(item.getInputStream());
JarEntry jarEntry;
while ((jarEntry = jis.getNextJarEntry()) != null) {
extract(jis, jarEntry, deployDir);
}
}
}
} catch (Exception e) {
LOG.error("Failed to upload to " + configPath, e);
}
}
}
use of org.apache.commons.fileupload.FileItem in project sonarqube by SonarSource.
the class CommonsMultipartRequestHandler method handleRequest.
/**
* <p> Parses the input stream and partitions the parsed items into a set
* of form fields and a set of file items. In the process, the parsed
* items are translated from Commons FileUpload <code>FileItem</code>
* instances to Struts <code>FormFile</code> instances. </p>
*
* @param request The multipart request to be processed.
* @throws ServletException if an unrecoverable error occurs.
*/
public void handleRequest(HttpServletRequest request) throws ServletException {
// Get the app config for the current request.
ModuleConfig ac = (ModuleConfig) request.getAttribute(Globals.MODULE_KEY);
// Create and configure a DIskFileUpload instance.
DiskFileUpload upload = new DiskFileUpload();
// The following line is to support an "EncodingFilter"
// see http://issues.apache.org/bugzilla/show_bug.cgi?id=23255
upload.setHeaderEncoding(request.getCharacterEncoding());
// Set the maximum size before a FileUploadException will be thrown.
upload.setSizeMax(getSizeMax(ac));
// Set the maximum size that will be stored in memory.
upload.setSizeThreshold((int) getSizeThreshold(ac));
// Set the the location for saving data on disk.
upload.setRepositoryPath(getRepositoryPath(ac));
// Create the hash tables to be populated.
elementsText = new Hashtable();
elementsFile = new Hashtable();
elementsAll = new Hashtable();
// Parse the request into file items.
List items = null;
try {
items = upload.parseRequest(request);
} catch (DiskFileUpload.SizeLimitExceededException e) {
// Special handling for uploads that are too big.
request.setAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED, Boolean.TRUE);
return;
} catch (FileUploadException e) {
log.error("Failed to parse multipart request", e);
throw new ServletException(e);
}
// Partition the items into form fields and files.
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
addTextParameter(request, item);
} else {
addFileParameter(item);
}
}
}
use of org.apache.commons.fileupload.FileItem in project OpenAttestation by OpenAttestation.
the class WLMDataController method uploadManifest.
public ModelAndView uploadManifest(HttpServletRequest req, HttpServletResponse res) {
log.info("WLMDataController.uploadManifest >>");
req.getSession().removeAttribute("manifestValue");
ModelAndView responseView = new ModelAndView(new JSONView());
List<Map<String, String>> manifestValue = new ArrayList<Map<String, String>>();
// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(req);
System.out.println(isMultipart);
if (!isMultipart) {
responseView.addObject("result", false);
return responseView;
}
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
try {
@SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(req);
// Process the uploaded items
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
String[] lines = item.getString().split("\\r?\\n");
for (String values : lines) {
if (values.length() > 2) {
String[] val = values.split(":");
if (val.length == 2) {
Map<String, String> manifest = new HashMap<String, String>();
manifest.put(val[0], val[1]);
manifestValue.add(manifest);
} else {
responseView.addObject("result", false);
return responseView;
}
}
}
}
}
log.info("Uploaded Content :: " + manifestValue.toString());
req.getSession().setAttribute("manifestValue", manifestValue);
/*responseView.addObject("manifestValue",manifestValue);*/
responseView.addObject("result", manifestValue.size() > 0 ? true : false);
} catch (FileUploadException e) {
e.printStackTrace();
responseView.addObject("result", false);
} catch (Exception e) {
e.printStackTrace();
responseView.addObject("result", false);
}
log.info("WLMDataController.uploadManifest <<<");
return responseView;
}
use of org.apache.commons.fileupload.FileItem in project OpenClinica by OpenClinica.
the class OpenRosaSubmissionController method doFieldDeletion.
/**
* @api {post} /pages/api/v2/editform/:studyOid/fieldsubmission Submit form data
* @apiName doSubmission
* @apiPermission admin
* @apiVersion 3.8.0
* @apiParam {String} studyOid Study Oid.
* @apiParam {String} ecid Key that will be used to look up subject context information while processing submission.
* @apiGroup Form
* @apiDescription Submits the data from a completed form.
*/
@RequestMapping(value = "/{studyOID}/fieldsubmission", method = RequestMethod.DELETE)
public ResponseEntity<String> doFieldDeletion(HttpServletRequest request, HttpServletResponse response, @PathVariable("studyOID") String studyOID, @RequestParam(FORM_CONTEXT) String ecid) {
logger.info("Processing xform field deletion.");
HashMap<String, String> subjectContext = null;
Locale locale = LocaleResolver.getLocale(request);
DataBinder dataBinder = new DataBinder(null);
Errors errors = dataBinder.getBindingResult();
Study study = studyDao.findByOcOID(studyOID);
String requestBody = null;
String instanceId = null;
HashMap<String, String> map = new HashMap();
ArrayList<HashMap> listOfUploadFilePaths = new ArrayList();
try {
// Verify Study is allowed to submit
if (!mayProceed(study)) {
logger.info("Field Deletions to the study not allowed. Aborting field submission.");
return new ResponseEntity<String>(HttpStatus.NOT_ACCEPTABLE);
}
String dir = getAttachedFilePath(studyOID);
FileProperties fileProperties = new FileProperties();
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(fileProperties.getFileSizeMax());
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
if (item.getFieldName().equals("instance_id")) {
instanceId = item.getString();
} else if (item.getFieldName().equals("xml_submission_fragment_file")) {
requestBody = item.getString("UTF-8");
} else if (item.getContentType() != null) {
if (!new File(dir).exists())
new File(dir).mkdirs();
File file = processUploadedFile(item, dir);
map.put(item.getFieldName(), file.getPath());
}
}
listOfUploadFilePaths.add(map);
if (instanceId == null) {
logger.info("Field Submissions to the study not allowed without a valid instanceId. Aborting field submission.");
return new ResponseEntity<String>(HttpStatus.NOT_ACCEPTABLE);
}
// Load user context from ecid
PFormCache cache = PFormCache.getInstance(context);
subjectContext = cache.getSubjectContext(ecid);
// Execute save as Hibernate transaction to avoid partial imports
openRosaSubmissionService.processFieldSubmissionRequest(study, subjectContext, instanceId, requestBody, errors, locale, listOfUploadFilePaths, SubmissionContainer.FieldRequestTypeEnum.DELETE_FIELD);
} catch (Exception e) {
logger.error("Exception while processing xform submission.");
logger.error(e.getMessage());
logger.error(ExceptionUtils.getStackTrace(e));
if (!errors.hasErrors()) {
// Send a failure response
logger.info("Submission caused internal error. Sending error response.");
return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
if (!errors.hasErrors()) {
// JsonLog submission with Participate
if (isParticipantSubmission(subjectContext))
notifier.notify(studyOID, subjectContext);
logger.info("Completed xform field submission. Sending successful response");
String responseMessage = "<OpenRosaResponse xmlns=\"http://openrosa.org/http/response\">" + "<message>success</message>" + "</OpenRosaResponse>";
return new ResponseEntity<String>(responseMessage, HttpStatus.CREATED);
} else {
logger.info("Field Submission contained errors. Sending error response");
return new ResponseEntity<String>(HttpStatus.NOT_ACCEPTABLE);
}
}
use of org.apache.commons.fileupload.FileItem in project libresonic by Libresonic.
the class UploadController method handleRequestInternal.
@RequestMapping(method = { RequestMethod.POST })
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
Map<String, Object> map = new HashMap<>();
List<File> uploadedFiles = new ArrayList<>();
List<File> unzippedFiles = new ArrayList<>();
TransferStatus status = null;
try {
status = statusService.createUploadStatus(playerService.getPlayer(request, response, false, false));
status.setBytesTotal(request.getContentLength());
request.getSession().setAttribute(UPLOAD_STATUS, status);
// Check that we have a file upload request
if (!ServletFileUpload.isMultipartContent(request)) {
throw new Exception("Illegal request.");
}
File dir = null;
boolean unzip = false;
UploadListener listener = new UploadListenerImpl(status);
FileItemFactory factory = new MonitoredDiskFileItemFactory(listener);
ServletFileUpload upload = new ServletFileUpload(factory);
List<?> items = upload.parseRequest(request);
// First, look for "dir" and "unzip" parameters.
for (Object o : items) {
FileItem item = (FileItem) o;
if (item.isFormField() && "dir".equals(item.getFieldName())) {
dir = new File(item.getString());
} else if (item.isFormField() && "unzip".equals(item.getFieldName())) {
unzip = true;
}
}
if (dir == null) {
throw new Exception("Missing 'dir' parameter.");
}
// Look for file items.
for (Object o : items) {
FileItem item = (FileItem) o;
if (!item.isFormField()) {
String fileName = item.getName();
if (fileName.trim().length() > 0) {
File targetFile = new File(dir, new File(fileName).getName());
if (!securityService.isUploadAllowed(targetFile)) {
throw new Exception("Permission denied: " + StringUtil.toHtml(targetFile.getPath()));
}
if (!dir.exists()) {
dir.mkdirs();
}
item.write(targetFile);
uploadedFiles.add(targetFile);
LOG.info("Uploaded " + targetFile);
if (unzip && targetFile.getName().toLowerCase().endsWith(".zip")) {
unzip(targetFile, unzippedFiles);
}
}
}
}
} catch (Exception x) {
LOG.warn("Uploading failed.", x);
map.put("exception", x);
} finally {
if (status != null) {
statusService.removeUploadStatus(status);
request.getSession().removeAttribute(UPLOAD_STATUS);
User user = securityService.getCurrentUser(request);
securityService.updateUserByteCounts(user, 0L, 0L, status.getBytesTransfered());
}
}
map.put("uploadedFiles", uploadedFiles);
map.put("unzippedFiles", unzippedFiles);
return new ModelAndView("upload", "model", map);
}
Aggregations