use of org.apache.commons.fileupload.disk.DiskFileItemFactory 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.disk.DiskFileItemFactory in project wicket by apache.
the class FileUploadTest method getInputStream.
/**
* Test that when getting an input stream a new input stream is returned every time.
*
* Also test that the inputstream is saved internally for later closing.
*
* @throws Exception
*/
@Test
public void getInputStream() throws Exception {
final IFileCleaner fileUploadCleaner = new FileCleaner();
DiskFileItemFactory itemFactory = new DiskFileItemFactory() {
@Override
public FileCleaningTracker getFileCleaningTracker() {
return new FileCleanerTrackerAdapter(fileUploadCleaner);
}
};
FileItem fileItem = itemFactory.createItem("dummyFieldName", "text/java", false, "FileUploadTest.java");
// Initialize the upload
fileItem.getOutputStream();
// Get the internal list out
Field inputStreamsField = FileUpload.class.getDeclaredField("inputStreamsToClose");
inputStreamsField.setAccessible(true);
FileUpload fileUpload = new FileUpload(fileItem);
List<?> inputStreams = (List<?>) inputStreamsField.get(fileUpload);
assertNull(inputStreams);
InputStream is1 = fileUpload.getInputStream();
inputStreams = (List<?>) inputStreamsField.get(fileUpload);
assertEquals(1, inputStreams.size());
InputStream is2 = fileUpload.getInputStream();
inputStreams = (List<?>) inputStreamsField.get(fileUpload);
assertEquals(2, inputStreams.size());
assertNotSame(is1, is2);
// Ok lets close all the streams
try {
fileUpload.closeStreams();
} catch (Exception e) {
fail();
}
inputStreams = (List<?>) inputStreamsField.get(fileUpload);
assertNull(inputStreams);
fileUploadCleaner.destroy();
}
use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project ff4j by ff4j.
the class ConsoleServlet method doPost.
/**
* {@inheritDoc}
*/
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String message = null;
String messagetype = "info";
try {
if (ServletFileUpload.isMultipartContent(req)) {
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(req);
for (FileItem item : items) {
if (item.isFormField()) {
if (OPERATION.equalsIgnoreCase(item.getFieldName())) {
LOGGER.info("Processing action : " + item.getString());
}
} else if (FLIPFILE.equalsIgnoreCase(item.getFieldName())) {
String filename = FilenameUtils.getName(item.getName());
if (filename.toLowerCase().endsWith("xml")) {
importFile(getFf4j(), item.getInputStream());
message = "The file <b>" + filename + "</b> has been successfully imported";
} else {
messagetype = ERROR;
message = "Invalid FILE, must be CSV, XML or PROPERTIES files";
}
}
}
} else {
String operation = req.getParameter(OPERATION);
String uid = req.getParameter(FEATID);
LOGGER.info("POST - op=" + operation + " feat=" + uid);
if (operation != null && !operation.isEmpty()) {
if (OP_EDIT_FEATURE.equalsIgnoreCase(operation)) {
updateFeatureDescription(getFf4j(), req);
message = msg(uid, "UPDATED");
} else if (OP_EDIT_PROPERTY.equalsIgnoreCase(operation)) {
updateProperty(getFf4j(), req);
message = renderMsgProperty(uid, "UPDATED");
} else if (OP_CREATE_PROPERTY.equalsIgnoreCase(operation)) {
createProperty(getFf4j(), req);
message = renderMsgProperty(req.getParameter(NAME), "ADDED");
} else if (OP_CREATE_FEATURE.equalsIgnoreCase(operation)) {
createFeature(getFf4j(), req);
message = msg(uid, "ADDED");
} else if (OP_TOGGLE_GROUP.equalsIgnoreCase(operation)) {
String groupName = req.getParameter(GROUPNAME);
if (groupName != null && !groupName.isEmpty()) {
String operationGroup = req.getParameter(SUBOPERATION);
if (OP_ENABLE.equalsIgnoreCase(operationGroup)) {
getFf4j().getFeatureStore().enableGroup(groupName);
message = renderMsgGroup(groupName, "ENABLED");
LOGGER.info("Group '" + groupName + "' has been ENABLED.");
} else if (OP_DISABLE.equalsIgnoreCase(operationGroup)) {
getFf4j().getFeatureStore().disableGroup(groupName);
message = renderMsgGroup(groupName, "DISABLED");
LOGGER.info("Group '" + groupName + "' has been DISABLED.");
}
}
} else {
LOGGER.error("Invalid POST OPERATION" + operation);
messagetype = ERROR;
message = "Invalid REQUEST";
}
} else {
LOGGER.error("No ID provided" + operation);
messagetype = ERROR;
message = "Invalid UID";
}
}
} catch (Exception e) {
messagetype = ERROR;
message = e.getMessage();
LOGGER.error("An error occured ", e);
}
// Update FF4J in Session (distributed)
getServletContext().setAttribute(FF4J_SESSIONATTRIBUTE_NAME, ff4j);
renderPage(ff4j, req, res, message, messagetype);
}
use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project ff4j by ff4j.
the class HomeController method post.
/**
* {@inheritDoc}
*/
public void post(HttpServletRequest req, HttpServletResponse res, WebContext ctx) throws Exception {
String msg = null;
String msgType = "success";
String operation = req.getParameter(WebConstants.OPERATION);
// Upload XML File
if (ServletFileUpload.isMultipartContent(req)) {
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(req);
for (FileItem item : items) {
if (item.isFormField()) {
if (OPERATION.equalsIgnoreCase(item.getFieldName())) {
LOGGER.info("Processing action : " + item.getString());
}
} else if (FLIPFILE.equalsIgnoreCase(item.getFieldName())) {
String filename = FilenameUtils.getName(item.getName());
if (filename.toLowerCase().endsWith("xml")) {
try {
importFile(getFf4j(), item.getInputStream());
msg = "The file <b>" + filename + "</b> has been successfully imported";
} catch (RuntimeException re) {
msgType = ERROR;
msg = "Cannot Import XML:" + re.getMessage();
break;
}
} else {
msgType = ERROR;
msg = "Invalid FILE, must be CSV, XML or PROPERTIES files";
}
}
}
ctx.setVariable("msgType", msgType);
ctx.setVariable("msgInfo", msg);
get(req, res, ctx);
} else if (WebConstants.OP_CREATE_SCHEMA.equalsIgnoreCase(operation)) {
try {
getFf4j().createSchema();
msg = "Schema has been created in DB (if required).";
ctx.setVariable("msgType", msgType);
ctx.setVariable("msgInfo", msg);
get(req, res, ctx);
} catch (RuntimeException re) {
ctx.setVariable("msgType", ERROR);
ctx.setVariable("msgInfo", "Cannot create Schema:" + re.getMessage());
ctx.setVariable(KEY_TITLE, "Home");
ctx.setVariable("today", Calendar.getInstance());
ctx.setVariable("homebean", new HomeBean());
}
} else if (WebConstants.OP_CLEAR_CACHE.equalsIgnoreCase(operation)) {
FF4jCacheProxy cacheProxy = getFf4j().getCacheProxy();
if (cacheProxy != null) {
cacheProxy.getCacheManager().clearFeatures();
cacheProxy.getCacheManager().clearProperties();
msg = "Cache Cleared!";
} else {
msg = "Cache not present: it cannot be cleared!";
}
ctx.setVariable("msgType", msgType);
ctx.setVariable("msgInfo", msg);
get(req, res, ctx);
}
}
use of org.apache.commons.fileupload.disk.DiskFileItemFactory 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
}
}
Aggregations