use of org.apache.commons.fileupload.servlet.ServletRequestContext in project felix by apache.
the class ServletRequestWrapper method handleMultipart.
private void handleMultipart() throws IOException {
// Create a new file upload handler
final ServletFileUpload upload = new ServletFileUpload();
upload.setSizeMax(this.multipartConfig.multipartMaxRequestSize);
upload.setFileSizeMax(this.multipartConfig.multipartMaxFileSize);
upload.setFileItemFactory(new DiskFileItemFactory(this.multipartConfig.multipartThreshold, new File(this.multipartConfig.multipartLocation)));
// Parse the request
List<FileItem> items = null;
try {
items = upload.parseRequest(new ServletRequestContext(this));
} catch (final FileUploadException fue) {
throw new IOException("Error parsing multipart request", fue);
}
parts = new ArrayList<>();
for (final FileItem item : items) {
parts.add(new Part() {
@Override
public InputStream getInputStream() throws IOException {
return item.getInputStream();
}
@Override
public String getContentType() {
return item.getContentType();
}
@Override
public String getName() {
return item.getFieldName();
}
@Override
public String getSubmittedFileName() {
return item.getName();
}
@Override
public long getSize() {
return item.getSize();
}
@Override
public void write(String fileName) throws IOException {
try {
item.write(new File(fileName));
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new IOException(e);
}
}
@Override
public void delete() throws IOException {
item.delete();
}
@Override
public String getHeader(String name) {
return item.getHeaders().getHeader(name);
}
@Override
public Collection<String> getHeaders(String name) {
final List<String> values = new ArrayList<>();
final Iterator<String> iter = item.getHeaders().getHeaders(name);
while (iter.hasNext()) {
values.add(iter.next());
}
return values;
}
@Override
public Collection<String> getHeaderNames() {
final List<String> names = new ArrayList<>();
final Iterator<String> iter = item.getHeaders().getHeaderNames();
while (iter.hasNext()) {
names.add(iter.next());
}
return names;
}
});
}
}
use of org.apache.commons.fileupload.servlet.ServletRequestContext in project Lucee by lucee.
the class FormImpl method initializeMultiPart.
private void initializeMultiPart(PageContext pc, boolean scriptProteced) {
// get temp directory
Resource tempDir = ((ConfigImpl) pc.getConfig()).getTempDirectory();
Resource tempFile;
// Create a new file upload handler
final String encoding = getEncoding();
FileItemFactory factory = tempDir instanceof File ? new DiskFileItemFactory(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD, (File) tempDir) : new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding(encoding);
// ServletRequestContext c = new ServletRequestContext(pc.getHttpServletRequest());
HttpServletRequest req = pc.getHttpServletRequest();
ServletRequestContext context = new ServletRequestContext(req) {
@Override
public String getCharacterEncoding() {
return encoding;
}
};
// Parse the request
try {
FileItemIterator iter = upload.getItemIterator(context);
// byte[] value;
InputStream is;
ArrayList<URLItem> list = new ArrayList<URLItem>();
String fileName;
while (iter.hasNext()) {
FileItemStream item = iter.next();
is = IOUtil.toBufferedInputStream(item.openStream());
if (item.getContentType() == null || StringUtil.isEmpty(item.getName())) {
list.add(new URLItem(item.getFieldName(), new String(IOUtil.toBytes(is), encoding), false));
} else {
fileName = getFileName();
tempFile = tempDir.getRealResource(fileName);
_fileItems.put(fileName, new Item(tempFile, item.getContentType(), item.getName(), item.getFieldName()));
String value = tempFile.toString();
IOUtil.copy(is, tempFile, true);
list.add(new URLItem(item.getFieldName(), value, false));
}
}
raw = list.toArray(new URLItem[list.size()]);
fillDecoded(raw, encoding, scriptProteced, pc.getApplicationContext().getSameFieldAsArray(SCOPE_FORM));
} catch (Exception e) {
SystemOut.printDate(e);
// throw new PageRuntimeException(Caster.toPageException(e));
fillDecodedEL(new URLItem[0], encoding, scriptProteced, pc.getApplicationContext().getSameFieldAsArray(SCOPE_FORM));
initException = e;
}
}
use of org.apache.commons.fileupload.servlet.ServletRequestContext in project acs-community-packaging by Alfresco.
the class UploadFileServlet method service.
/**
* @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@SuppressWarnings("unchecked")
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String uploadId = null;
String returnPage = null;
final RequestContext requestContext = new ServletRequestContext(request);
boolean isMultipart = ServletFileUpload.isMultipartContent(requestContext);
try {
AuthenticationStatus status = servletAuthenticate(request, response);
if (status == AuthenticationStatus.Failure) {
return;
}
if (!isMultipart) {
throw new AlfrescoRuntimeException("This servlet can only be used to handle file upload requests, make" + "sure you have set the enctype attribute on your form to multipart/form-data");
}
if (logger.isDebugEnabled())
logger.debug("Uploading servlet servicing...");
FacesContext context = FacesContext.getCurrentInstance();
Map<Object, Object> session = context.getExternalContext().getSessionMap();
ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
// ensure that the encoding is handled correctly
upload.setHeaderEncoding("UTF-8");
List<FileItem> fileItems = upload.parseRequest(request);
FileUploadBean bean = new FileUploadBean();
for (FileItem item : fileItems) {
if (item.isFormField()) {
if (item.getFieldName().equalsIgnoreCase("return-page")) {
returnPage = item.getString();
} else if (item.getFieldName().equalsIgnoreCase("upload-id")) {
uploadId = item.getString();
}
} else {
String filename = item.getName();
if (filename != null && filename.length() != 0) {
if (logger.isDebugEnabled()) {
logger.debug("Processing uploaded file: " + filename);
}
// ADB-41: Ignore non-existent files i.e. 0 byte streams.
if (allowZeroByteFiles() == true || item.getSize() > 0) {
// workaround a bug in IE where the full path is returned
// IE is only available for Windows so only check for the Windows path separator
filename = FilenameUtils.getName(filename);
final File tempFile = TempFileProvider.createTempFile("alfresco", ".upload");
item.write(tempFile);
bean.setFile(tempFile);
bean.setFileName(filename);
bean.setFilePath(tempFile.getAbsolutePath());
if (logger.isDebugEnabled()) {
logger.debug("Temp file: " + tempFile.getAbsolutePath() + " size " + tempFile.length() + " bytes created from upload filename: " + filename);
}
} else {
if (logger.isWarnEnabled())
logger.warn("Ignored file '" + filename + "' as there was no content, this is either " + "caused by uploading an empty file or a file path that does not exist on the client.");
}
}
}
}
session.put(FileUploadBean.getKey(uploadId), bean);
if (bean.getFile() == null && uploadId != null && logger.isWarnEnabled()) {
logger.warn("no file uploaded for upload id: " + uploadId);
}
if (returnPage == null || returnPage.length() == 0) {
throw new AlfrescoRuntimeException("return-page parameter has not been supplied");
}
JSONObject json;
try {
json = new JSONObject(returnPage);
if (json.has("id") && json.has("args")) {
// finally redirect
if (logger.isDebugEnabled()) {
logger.debug("Sending back javascript response " + returnPage);
}
response.setContentType(MimetypeMap.MIMETYPE_HTML);
response.setCharacterEncoding("utf-8");
// work-around for WebKit protection against embedded javascript on POST body response
response.setHeader("X-XSS-Protection", "0");
final PrintWriter out = response.getWriter();
out.println("<html><body><script type=\"text/javascript\">");
out.println("window.parent.upload_complete_helper(");
out.println("'" + json.getString("id") + "'");
out.println(", ");
out.println(json.getJSONObject("args"));
out.println(");");
out.println("</script></body></html>");
out.close();
}
} catch (JSONException e) {
// finally redirect
if (logger.isDebugEnabled())
logger.debug("redirecting to: " + returnPage);
response.sendRedirect(returnPage);
}
if (logger.isDebugEnabled())
logger.debug("upload complete");
} catch (Throwable error) {
handleUploadException(request, response, error, returnPage);
}
}
use of org.apache.commons.fileupload.servlet.ServletRequestContext in project openmrs-core by openmrs.
the class StartupErrorFilter method doPost.
/**
* @see org.openmrs.web.filter.StartupFilter#doPost(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/
@Override
protected void doPost(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException, ServletException {
// if they are uploading modules
if (getModel().errorAtStartup instanceof OpenmrsCoreModuleException) {
RequestContext requestContext = new ServletRequestContext(httpRequest);
if (!ServletFileUpload.isMultipartContent(requestContext)) {
throw new ServletException("The request is not a valid multipart/form-data upload request");
}
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
Context.openSession();
List<FileItem> items = upload.parseRequest(requestContext);
for (FileItem item : items) {
InputStream uploadedStream = item.getInputStream();
ModuleUtil.insertModuleFile(uploadedStream, item.getName());
}
} catch (FileUploadException ex) {
throw new ServletException("Error while uploading file(s)", ex);
} finally {
Context.closeSession();
}
Map<String, Object> map = new HashMap<>();
map.put("success", Boolean.TRUE);
renderTemplate("coremoduleerror.vm", map, httpResponse);
// TODO restart openmrs here instead of going to coremodulerror template
}
}
use of org.apache.commons.fileupload.servlet.ServletRequestContext in project tomee by apache.
the class CommonsFileUploadPartFactory method read.
public static Collection<Part> read(final HttpRequestImpl request) {
// mainly for testing
// Create a new file upload handler
final DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setRepository(REPO);
final ServletFileUpload upload = new ServletFileUpload();
upload.setFileItemFactory(factory);
final List<Part> parts = new ArrayList<>();
try {
final List<FileItem> items = upload.parseRequest(new ServletRequestContext(request));
final String enc = request.getCharacterEncoding();
for (final FileItem item : items) {
final CommonsFileUploadPart part = new CommonsFileUploadPart(item, null);
parts.add(part);
if (part.getSubmittedFileName() == null) {
String name = part.getName();
String value = null;
try {
String encoding = request.getCharacterEncoding();
if (encoding == null) {
if (enc == null) {
encoding = "UTF-8";
} else {
encoding = enc;
}
}
value = part.getString(encoding);
} catch (final UnsupportedEncodingException uee) {
try {
value = part.getString("UTF-8");
} catch (final UnsupportedEncodingException e) {
// not possible
}
}
request.addInternalParameter(name, value);
}
}
return parts;
} catch (final FileUploadException e) {
throw new IllegalStateException(e);
}
}
Aggregations