use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project fabric8 by jboss-fuse.
the class MavenProxyServletSupportTest method testUploadWithMimeMultipartFormData.
@Test
public void testUploadWithMimeMultipartFormData() throws Exception {
new File("target/maven/proxy/tmp/multipart").mkdirs();
System.setProperty("karaf.data", new File("target").getCanonicalPath());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JarOutputStream jas = new JarOutputStream(baos);
addEntry(jas, "META-INF/MANIFEST.MF", "Manifest-Version: 1.0\n".getBytes());
addEntry(jas, "META-INF/maven/io.fabric8/mybundle/pom.properties", "groupId=io.fabric8\nartifactId=mybundle\nversion=1.0\n".getBytes());
jas.close();
byte[] jarBytes = baos.toByteArray();
RuntimeProperties props = new MockRuntimeProperties();
MavenResolver resolver = EasyMock.createMock(MavenResolver.class);
MavenUploadProxyServlet servlet = new MavenUploadProxyServlet(resolver, props, projectDeployer, new File("target/upload"), 0);
servlet.setFileItemFactory(new DiskFileItemFactory(0, new File("target/maven/proxy/tmp/multipart")));
HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
FilePart part = new FilePart("file[]", new ByteArrayPartSource("mybundle-1.0.jar", jarBytes));
MultipartRequestEntity entity = new MultipartRequestEntity(new Part[] { part }, new HttpMethodParams());
final ByteArrayOutputStream requestBytes = new ByteArrayOutputStream();
entity.writeRequest(requestBytes);
final byte[] multipartRequestBytes = requestBytes.toByteArray();
EasyMock.expect(request.getPathInfo()).andReturn("/mybundle-1.0.jar");
EasyMock.expect(request.getHeader(MavenProxyServletSupport.LOCATION_HEADER)).andReturn(null);
EasyMock.expect(request.getParameter("profile")).andReturn("my");
EasyMock.expect(request.getParameter("version")).andReturn("1.0");
EasyMock.expect(request.getContentType()).andReturn(entity.getContentType()).anyTimes();
EasyMock.expect(request.getHeader("Content-length")).andReturn(Long.toString(entity.getContentLength())).anyTimes();
EasyMock.expect(request.getContentLength()).andReturn((int) entity.getContentLength()).anyTimes();
EasyMock.expect(request.getCharacterEncoding()).andReturn("ISO-8859-1").anyTimes();
Capture<String> location = EasyMock.newCapture(CaptureType.ALL);
response.setStatus(HttpServletResponse.SC_ACCEPTED);
EasyMock.expect(request.getInputStream()).andReturn(new ServletInputStream() {
private int pos = 0;
@Override
public int read() throws IOException {
return pos >= multipartRequestBytes.length ? -1 : (multipartRequestBytes[pos++] & 0xFF);
}
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return true;
}
@Override
public void setReadListener(ReadListener readListener) {
}
});
Capture<ProjectRequirements> requirementsCapture = EasyMock.newCapture(CaptureType.FIRST);
EasyMock.expect(projectDeployer.deployProject(EasyMock.capture(requirementsCapture), EasyMock.eq(true))).andReturn(null);
EasyMock.replay(resolver, request, response, projectDeployer);
servlet.doPut(request, response);
FileInputStream fis = new FileInputStream("target/upload/io.fabric8/mybundle/1.0/mybundle-1.0.jar");
ByteArrayOutputStream storedBundleBytes = new ByteArrayOutputStream();
IOUtils.copy(fis, storedBundleBytes);
fis.close();
Assert.assertArrayEquals(jarBytes, storedBundleBytes.toByteArray());
ProjectRequirements pr = requirementsCapture.getValue();
List<String> bundles = pr.getBundles();
assertThat(bundles.size(), equalTo(1));
assertThat(bundles.get(0), equalTo("mvn:io.fabric8/mybundle/1.0"));
assertThat(pr.getProfileId(), equalTo("my"));
assertThat(pr.getVersion(), equalTo("1.0"));
assertThat(pr.getGroupId(), nullValue());
assertThat(pr.getArtifactId(), nullValue());
EasyMock.verify(resolver, request, response, projectDeployer);
}
use of org.apache.commons.fileupload.disk.DiskFileItemFactory 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.disk.DiskFileItemFactory in project ofbiz-framework by apache.
the class LayoutWorker method uploadImageAndParameters.
/**
* Uploads image data from a form and stores it in ImageDataResource.
* Expects key data in a field identitified by the "idField" value
* and the binary data to be in a field id'd by uploadField.
*/
public static Map<String, Object> uploadImageAndParameters(HttpServletRequest request, String uploadField) {
Locale locale = UtilHttp.getLocale(request);
Map<String, Object> results = new HashMap<String, Object>();
Map<String, String> formInput = new HashMap<String, String>();
results.put("formInput", formInput);
ServletFileUpload fu = new ServletFileUpload(new DiskFileItemFactory(10240, new File(new File("runtime"), "tmp")));
List<FileItem> lst = null;
try {
lst = UtilGenerics.checkList(fu.parseRequest(request));
} catch (FileUploadException e4) {
return ServiceUtil.returnError(e4.getMessage());
}
if (lst.size() == 0) {
String errMsg = UtilProperties.getMessage(err_resource, "layoutEvents.no_files_uploaded", locale);
request.setAttribute("_ERROR_MESSAGE_", errMsg);
return ServiceUtil.returnError(UtilProperties.getMessage(err_resource, "layoutEvents.no_files_uploaded", locale));
}
// This code finds the idField and the upload FileItems
FileItem fi = null;
FileItem imageFi = null;
for (int i = 0; i < lst.size(); i++) {
fi = lst.get(i);
String fieldName = fi.getFieldName();
String fieldStr = fi.getString();
if (fi.isFormField()) {
formInput.put(fieldName, fieldStr);
request.setAttribute(fieldName, fieldStr);
}
if (fieldName.equals(uploadField)) {
imageFi = fi;
// MimeType of upload file
results.put("uploadMimeType", fi.getContentType());
}
}
if (imageFi == null) {
String errMsg = UtilProperties.getMessage(err_resource, "layoutEvents.image_null", UtilMisc.toMap("imageFi", imageFi), locale);
request.setAttribute("_ERROR_MESSAGE_", errMsg);
return null;
}
byte[] imageBytes = imageFi.get();
ByteBuffer byteWrap = ByteBuffer.wrap(imageBytes);
results.put("imageData", byteWrap);
results.put("imageFileName", imageFi.getName());
return results;
}
use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project ofbiz-framework by apache.
the class DataResourceWorker method uploadAndStoreImage.
/**
* Uploads image data from a form and stores it in ImageDataResource. Expects key data in a field identified by the "idField" value and the binary data
* to be in a field id'd by uploadField.
*/
// TODO: This method is not used and should be removed. amb
public static String uploadAndStoreImage(HttpServletRequest request, String idField, String uploadField) {
ServletFileUpload fu = new ServletFileUpload(new DiskFileItemFactory(10240, FileUtil.getFile("runtime/tmp")));
List<FileItem> lst = null;
Locale locale = UtilHttp.getLocale(request);
try {
lst = UtilGenerics.checkList(fu.parseRequest(request));
} catch (FileUploadException e) {
request.setAttribute("_ERROR_MESSAGE_", e.toString());
return "error";
}
if (lst.size() == 0) {
String errMsg = UtilProperties.getMessage(DataResourceWorker.err_resource, "dataResourceWorker.no_files_uploaded", locale);
request.setAttribute("_ERROR_MESSAGE_", errMsg);
Debug.logWarning("[DataEvents.uploadImage] No files uploaded", module);
return "error";
}
// This code finds the idField and the upload FileItems
FileItem fi = null;
FileItem imageFi = null;
String imageFileName = null;
Map<String, Object> passedParams = new HashMap<>();
HttpSession session = request.getSession();
GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
passedParams.put("userLogin", userLogin);
byte[] imageBytes = null;
for (int i = 0; i < lst.size(); i++) {
fi = lst.get(i);
String fieldName = fi.getFieldName();
if (fi.isFormField()) {
String fieldStr = fi.getString();
passedParams.put(fieldName, fieldStr);
} else if (fieldName.startsWith("imageData")) {
imageFi = fi;
imageBytes = imageFi.get();
passedParams.put(fieldName, imageBytes);
imageFileName = imageFi.getName();
passedParams.put("drObjectInfo", imageFileName);
if (Debug.infoOn()) {
Debug.logInfo("[UploadContentAndImage]imageData: " + imageBytes.length, module);
}
}
}
if (imageBytes != null && imageBytes.length > 0) {
String mimeType = getMimeTypeFromImageFileName(imageFileName);
if (UtilValidate.isNotEmpty(mimeType)) {
passedParams.put("drMimeTypeId", mimeType);
try {
String returnMsg = UploadContentAndImage.processContentUpload(passedParams, "", request);
if ("error".equals(returnMsg)) {
return "error";
}
} catch (GenericServiceException e) {
request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
return "error";
}
} else {
request.setAttribute("_ERROR_MESSAGE_", "mimeType is empty.");
return "error";
}
}
return "success";
}
use of org.apache.commons.fileupload.disk.DiskFileItemFactory 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();
}
Aggregations