use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project ofbiz-framework by apache.
the class UploadContentAndImage method uploadContentStuff.
public static String uploadContentStuff(HttpServletRequest request, HttpServletResponse response) {
try {
HttpSession session = request.getSession();
GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
ServletFileUpload dfu = new ServletFileUpload(new DiskFileItemFactory(10240, FileUtil.getFile("runtime/tmp")));
List<FileItem> lst = null;
try {
lst = UtilGenerics.checkList(dfu.parseRequest(request));
} catch (FileUploadException e4) {
request.setAttribute("_ERROR_MESSAGE_", e4.getMessage());
Debug.logError("[UploadContentAndImage.uploadContentAndImage] " + e4.getMessage(), module);
return "error";
}
if (lst.size() == 0) {
request.setAttribute("_ERROR_MESSAGE_", "No files uploaded");
Debug.logWarning("[DataEvents.uploadImage] No files uploaded", module);
return "error";
}
Map<String, Object> passedParams = new HashMap<String, Object>();
FileItem fi = null;
FileItem imageFi = null;
byte[] imageBytes;
passedParams.put("userLogin", userLogin);
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;
String fileName = fi.getName();
passedParams.put("drObjectInfo", fileName);
String contentType = fi.getContentType();
passedParams.put("drMimeTypeId", contentType);
imageBytes = imageFi.get();
passedParams.put(fieldName, imageBytes);
if (Debug.infoOn()) {
Debug.logInfo("[UploadContentAndImage]imageData: " + imageBytes.length, module);
}
}
}
if (Debug.infoOn()) {
Debug.logInfo("[UploadContentAndImage]passedParams: " + passedParams, module);
}
// The number of multi form rows is retrieved
int rowCount = UtilHttp.getMultiFormRowCount(request);
if (rowCount < 1) {
rowCount = 1;
}
TransactionUtil.begin();
for (int i = 0; i < rowCount; i++) {
String suffix = "_o_" + i;
if (i == 0) {
suffix = "";
}
String returnMsg = processContentUpload(passedParams, suffix, request);
if ("error".equals(returnMsg)) {
try {
TransactionUtil.rollback();
} catch (GenericTransactionException e2) {
ServiceUtil.setMessages(request, e2.getMessage(), null, null);
return "error";
}
return "error";
}
}
TransactionUtil.commit();
} catch (GenericTransactionException | GenericServiceException e) {
Debug.logError(e, "[UploadContentAndImage] ", module);
request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
try {
TransactionUtil.rollback();
} catch (GenericTransactionException e2) {
request.setAttribute("_ERROR_MESSAGE_", e2.getMessage());
return "error";
}
return "error";
}
return "success";
}
use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project ofbiz-framework by apache.
the class UploadContentAndImage method uploadContentAndImage.
public static String uploadContentAndImage(HttpServletRequest request, HttpServletResponse response) {
try {
Locale locale = UtilHttp.getLocale(request);
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
Delegator delegator = (Delegator) request.getAttribute("delegator");
HttpSession session = request.getSession();
GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
ServletFileUpload dfu = new ServletFileUpload(new DiskFileItemFactory(10240, FileUtil.getFile("runtime/tmp")));
List<FileItem> lst = null;
try {
lst = UtilGenerics.checkList(dfu.parseRequest(request));
} catch (FileUploadException e4) {
request.setAttribute("_ERROR_MESSAGE_", e4.getMessage());
Debug.logError("[UploadContentAndImage.uploadContentAndImage] " + e4.getMessage(), module);
return "error";
}
if (lst.size() == 0) {
String errMsg = UtilProperties.getMessage(UploadContentAndImage.err_resource, "uploadContentAndImage.no_files_uploaded", locale);
request.setAttribute("_ERROR_MESSAGE_", errMsg);
Debug.logWarning("[DataEvents.uploadImage] No files uploaded", module);
return "error";
}
Map<String, Object> passedParams = new HashMap<String, Object>();
FileItem fi = null;
FileItem imageFi = null;
byte[] imageBytes = {};
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 ("imageData".equals(fieldName)) {
imageFi = fi;
imageBytes = imageFi.get();
}
}
if (Debug.infoOn()) {
Debug.logInfo("[UploadContentAndImage]passedParams: " + passedParams, module);
}
TransactionUtil.begin();
List<String> contentPurposeList = ContentWorker.prepContentPurposeList(passedParams);
passedParams.put("contentPurposeList", contentPurposeList);
String entityOperation = (String) passedParams.get("entityOperation");
String passedContentId = (String) passedParams.get("ftlContentId");
List<String> targetOperationList = ContentWorker.prepTargetOperationList(passedParams, entityOperation);
passedParams.put("targetOperationList", targetOperationList);
// Create or update FTL template
Map<String, Object> ftlContext = new HashMap<String, Object>();
ftlContext.put("userLogin", userLogin);
ftlContext.put("contentId", passedParams.get("ftlContentId"));
ftlContext.put("ownerContentId", passedParams.get("ownerContentId"));
String contentTypeId = (String) passedParams.get("contentTypeId");
ftlContext.put("contentTypeId", contentTypeId);
ftlContext.put("statusId", passedParams.get("statusId"));
ftlContext.put("contentPurposeList", UtilMisc.toList(passedParams.get("contentPurposeList")));
ftlContext.put("contentPurposeList", contentPurposeList);
ftlContext.put("targetOperationList", targetOperationList);
ftlContext.put("contentName", passedParams.get("contentName"));
ftlContext.put("dataTemplateTypeId", passedParams.get("dataTemplateTypeId"));
ftlContext.put("description", passedParams.get("description"));
ftlContext.put("privilegeEnumId", passedParams.get("privilegeEnumId"));
String drid = (String) passedParams.get("dataResourceId");
ftlContext.put("dataResourceId", drid);
// inhibits persistence of DataResource, because it already exists
ftlContext.put("dataResourceTypeId", null);
String contentIdTo = (String) passedParams.get("contentIdTo");
ftlContext.put("contentIdTo", contentIdTo);
String contentAssocTypeId = (String) passedParams.get("contentAssocTypeId");
// Don't post assoc at this time
ftlContext.put("contentAssocTypeId", null);
Map<String, Object> ftlResults = dispatcher.runSync("persistContentAndAssoc", ftlContext);
if (ServiceUtil.isError(ftlResults)) {
String errorMessage = ServiceUtil.getErrorMessage(ftlResults);
request.setAttribute("_ERROR_MESSAGE_", errorMessage);
Debug.logError(errorMessage, module);
TransactionUtil.rollback();
return "error";
}
String ftlContentId = (String) ftlResults.get("contentId");
if (UtilValidate.isNotEmpty(contentIdTo)) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("fromDate", UtilDateTime.nowTimestamp());
map.put("contentId", ftlContentId);
map.put("contentIdTo", contentIdTo);
map.put("userLogin", userLogin);
if (UtilValidate.isEmpty(contentAssocTypeId) && UtilValidate.isEmpty(passedContentId) && UtilValidate.isNotEmpty(contentIdTo)) {
// switch the association order because we are really not linking to the forum
// but showing that this content is released to that forum.
map.put("contentIdTo", ftlContentId);
map.put("contentId", contentIdTo);
map.put("contentAssocTypeId", "PUBLISH_RELEASE");
} else if ("PUBLISH_LINK".equals(contentAssocTypeId)) {
map.put("contentAssocTypeId", "PUBLISH_LINK");
String publishOperation = (String) passedParams.get("publishOperation");
if (UtilValidate.isEmpty(publishOperation)) {
publishOperation = "CONTENT_PUBLISH";
}
map.put("targetOperationList", StringUtil.split(publishOperation, "|"));
map.put("targetOperationString", null);
} else {
map.put("contentAssocTypeId", contentAssocTypeId);
}
if (UtilValidate.isNotEmpty(map.get("contentAssocTypeId"))) {
ftlResults = dispatcher.runSync("createContentAssoc", map);
if (ServiceUtil.isError(ftlResults)) {
String errorMessage = ServiceUtil.getErrorMessage(ftlResults);
request.setAttribute("_ERROR_MESSAGE_", errorMessage);
Debug.logError(errorMessage, module);
TransactionUtil.rollback();
return "error";
}
}
}
if (UtilValidate.isEmpty(ftlContentId)) {
ftlContentId = passedContentId;
}
String ftlDataResourceId = drid;
if (Debug.infoOn())
Debug.logInfo("[UploadContentAndImage]ftlContentId:" + ftlContentId, module);
// Create or update summary text subContent
if (passedParams.containsKey("summaryData")) {
Map<String, Object> sumContext = new HashMap<String, Object>();
sumContext.put("userLogin", userLogin);
sumContext.put("contentId", passedParams.get("sumContentId"));
sumContext.put("ownerContentId", ftlContentId);
sumContext.put("contentTypeId", "DOCUMENT");
sumContext.put("statusId", passedParams.get("statusId"));
sumContext.put("contentPurposeList", UtilMisc.toList("SUMMARY"));
sumContext.put("targetOperationList", targetOperationList);
sumContext.put("contentName", passedParams.get("contentName"));
sumContext.put("description", passedParams.get("description"));
sumContext.put("privilegeEnumId", passedParams.get("privilegeEnumId"));
sumContext.put("dataResourceId", passedParams.get("sumDataResourceId"));
sumContext.put("dataResourceTypeId", "ELECTRONIC_TEXT");
sumContext.put("contentIdTo", ftlContentId);
sumContext.put("contentAssocTypeId", "SUB_CONTENT");
sumContext.put("textData", passedParams.get("summaryData"));
sumContext.put("mapKey", "SUMMARY");
sumContext.put("dataTemplateTypeId", "NONE");
Map<String, Object> sumResults = dispatcher.runSync("persistContentAndAssoc", sumContext);
if (ServiceUtil.isError(ftlResults)) {
String errorMessage = ServiceUtil.getErrorMessage(ftlResults);
request.setAttribute("_ERROR_MESSAGE_", errorMessage);
Debug.logError(errorMessage, module);
TransactionUtil.rollback();
return "error";
}
}
// Create or update electronic text subContent
if (passedParams.containsKey("textData")) {
Map<String, Object> txtContext = new HashMap<String, Object>();
txtContext.put("userLogin", userLogin);
txtContext.put("contentId", passedParams.get("txtContentId"));
txtContext.put("ownerContentId", ftlContentId);
txtContext.put("contentTypeId", "DOCUMENT");
txtContext.put("statusId", passedParams.get("statusId"));
txtContext.put("contentPurposeList", UtilMisc.toList("MAIN_ARTICLE"));
txtContext.put("targetOperationList", targetOperationList);
txtContext.put("contentName", passedParams.get("contentName"));
txtContext.put("description", passedParams.get("description"));
txtContext.put("privilegeEnumId", passedParams.get("privilegeEnumId"));
txtContext.put("dataResourceId", passedParams.get("txtDataResourceId"));
txtContext.put("dataResourceTypeId", "ELECTRONIC_TEXT");
txtContext.put("contentIdTo", ftlContentId);
txtContext.put("contentAssocTypeId", "SUB_CONTENT");
txtContext.put("textData", passedParams.get("textData"));
txtContext.put("mapKey", "ARTICLE");
txtContext.put("dataTemplateTypeId", "NONE");
Map<String, Object> txtResults = dispatcher.runSync("persistContentAndAssoc", txtContext);
if (ServiceUtil.isError(ftlResults)) {
String errorMessage = ServiceUtil.getErrorMessage(ftlResults);
request.setAttribute("_ERROR_MESSAGE_", errorMessage);
Debug.logError(errorMessage, module);
TransactionUtil.rollback();
return "error";
}
}
// Create or update image subContent
Map<String, Object> imgContext = new HashMap<String, Object>();
if (imageBytes.length > 0) {
imgContext.put("userLogin", userLogin);
imgContext.put("contentId", passedParams.get("imgContentId"));
imgContext.put("ownerContentId", ftlContentId);
imgContext.put("contentTypeId", "DOCUMENT");
imgContext.put("statusId", passedParams.get("statusId"));
imgContext.put("contentName", passedParams.get("contentName"));
imgContext.put("description", passedParams.get("description"));
imgContext.put("contentPurposeList", contentPurposeList);
imgContext.put("privilegeEnumId", passedParams.get("privilegeEnumId"));
imgContext.put("targetOperationList", targetOperationList);
imgContext.put("dataResourceId", passedParams.get("imgDataResourceId"));
String dataResourceTypeId = "IMAGE_OBJECT";
imgContext.put("dataResourceTypeId", dataResourceTypeId);
imgContext.put("contentIdTo", ftlContentId);
imgContext.put("contentAssocTypeId", "SUB_CONTENT");
imgContext.put("imageData", imageBytes);
imgContext.put("mapKey", "IMAGE");
imgContext.put("dataTemplateTypeId", "NONE");
imgContext.put("rootDir", "rootDir");
if (Debug.infoOn())
Debug.logInfo("[UploadContentAndImage]imgContext " + imgContext, module);
Map<String, Object> imgResults = dispatcher.runSync("persistContentAndAssoc", imgContext);
if (ServiceUtil.isError(ftlResults)) {
String errorMessage = ServiceUtil.getErrorMessage(ftlResults);
request.setAttribute("_ERROR_MESSAGE_", errorMessage);
Debug.logError(errorMessage, module);
TransactionUtil.rollback();
return "error";
}
}
// Check for existing AUTHOR link
String userLoginId = userLogin.getString("userLoginId");
GenericValue authorContent = EntityQuery.use(delegator).from("Content").where("contentId", userLoginId).cache().queryOne();
if (authorContent != null) {
long currentAuthorAssocCount = EntityQuery.use(delegator).from("ContentAssoc").where("contentId", ftlContentId, "contentIdTo", userLoginId, "contentAssocTypeId", "AUTHOR").filterByDate().queryCount();
if (currentAuthorAssocCount == 0) {
// Don't want to bother with permission checking on this association
GenericValue authorAssoc = delegator.makeValue("ContentAssoc");
authorAssoc.set("contentId", ftlContentId);
authorAssoc.set("contentIdTo", userLoginId);
authorAssoc.set("contentAssocTypeId", "AUTHOR");
authorAssoc.set("fromDate", UtilDateTime.nowTimestamp());
authorAssoc.set("createdByUserLogin", userLoginId);
authorAssoc.set("lastModifiedByUserLogin", userLoginId);
authorAssoc.set("createdDate", UtilDateTime.nowTimestamp());
authorAssoc.set("lastModifiedDate", UtilDateTime.nowTimestamp());
authorAssoc.create();
}
}
request.setAttribute("dataResourceId", ftlDataResourceId);
request.setAttribute("drDataResourceId", ftlDataResourceId);
request.setAttribute("contentId", ftlContentId);
request.setAttribute("masterContentId", ftlContentId);
request.setAttribute("contentIdTo", contentIdTo);
String newTrail = passedParams.get("nodeTrailCsv") + "," + ftlContentId;
request.setAttribute("nodeTrailCsv", newTrail);
request.setAttribute("passedParams", passedParams);
TransactionUtil.commit();
} catch (GenericEntityException | GenericServiceException e) {
Debug.logError(e, "[UploadContentAndImage] ", module);
request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
try {
TransactionUtil.rollback();
} catch (GenericTransactionException e2) {
request.setAttribute("_ERROR_MESSAGE_", e2.getMessage());
return "error";
}
return "error";
}
return "success";
}
use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project coastal-hazards by USGS-CIDA.
the class FormUploadHandler method saveFileFromRequest.
public static File saveFileFromRequest(HttpServletRequest request, String filenameParameter, File destinationFile) throws FileUploadException, IOException {
if (StringUtils.isBlank(filenameParameter)) {
throw new IllegalArgumentException();
}
if (ServletFileUpload.isMultipartContent(request)) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
FileItemIterator iter;
iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
if (filenameParameter.toLowerCase().equals(name.toLowerCase())) {
FileHelper.saveFileFromInputStream(item.openStream(), destinationFile);
break;
}
}
} else {
FileHelper.saveFileFromInputStream(request.getInputStream(), destinationFile);
}
return destinationFile;
}
use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project structr by structr.
the class DeploymentServlet method init.
@Override
public void init() {
try (final Tx tx = StructrApp.getInstance().tx()) {
DiskFileItemFactory fileFactory = new DiskFileItemFactory();
fileFactory.setSizeThreshold(MEMORY_THRESHOLD);
// new File(Services.getInstance().getTmpPath());
filesDir = new File(Settings.TmpPath.getValue());
if (!filesDir.exists()) {
filesDir.mkdir();
}
fileFactory.setRepository(filesDir);
uploader = new ServletFileUpload(fileFactory);
tx.success();
} catch (FrameworkException t) {
logger.warn("", t);
}
}
use of org.apache.commons.fileupload.disk.DiskFileItemFactory in project com-liferay-apio-architect by liferay.
the class MultipartBodyMessageBodyReader method readFrom.
@Override
public Body readFrom(Class<Body> clazz, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException {
if (!isMultipartContent(_httpServletRequest)) {
throw new BadRequestException("Request body is not a valid multipart form");
}
FileItemFactory fileItemFactory = new DiskFileItemFactory();
ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
try {
List<FileItem> fileItems = servletFileUpload.parseRequest(_httpServletRequest);
Iterator<FileItem> iterator = fileItems.iterator();
Map<String, String> values = new HashMap<>();
Map<String, BinaryFile> binaryFiles = new HashMap<>();
Map<String, Map<Integer, String>> indexedValueLists = new HashMap<>();
Map<String, Map<Integer, BinaryFile>> indexedFileLists = new HashMap<>();
while (iterator.hasNext()) {
FileItem fileItem = iterator.next();
String name = fileItem.getFieldName();
Matcher matcher = _arrayPattern.matcher(name);
if (matcher.matches()) {
int index = Integer.parseInt(matcher.group(2));
String actualName = matcher.group(1);
_storeFileItem(fileItem, value -> {
Map<Integer, String> indexedMap = indexedValueLists.computeIfAbsent(actualName, __ -> new HashMap<>());
indexedMap.put(index, value);
}, binaryFile -> {
Map<Integer, BinaryFile> indexedMap = indexedFileLists.computeIfAbsent(actualName, __ -> new HashMap<>());
indexedMap.put(index, binaryFile);
});
} else {
_storeFileItem(fileItem, value -> values.put(name, value), binaryFile -> binaryFiles.put(name, binaryFile));
}
}
Map<String, List<String>> valueLists = _flattenMap(indexedValueLists);
Map<String, List<BinaryFile>> fileLists = _flattenMap(indexedFileLists);
return Body.create(key -> Optional.ofNullable(values.get(key)), key -> Optional.ofNullable(valueLists.get(key)), key -> Optional.ofNullable(fileLists.get(key)), key -> Optional.ofNullable(binaryFiles.get(key)));
} catch (FileUploadException | IndexOutOfBoundsException | NumberFormatException e) {
throw new BadRequestException("Request body is not a valid multipart form", e);
}
}
Aggregations