Search in sources :

Example 61 with FileUploadException

use of org.apache.commons.fileupload.FileUploadException 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;
}
Also used : Locale(java.util.Locale) HashMap(java.util.HashMap) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) ByteBuffer(java.nio.ByteBuffer) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) File(java.io.File) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 62 with FileUploadException

use of org.apache.commons.fileupload.FileUploadException 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";
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) HashMap(java.util.HashMap) HttpSession(javax.servlet.http.HttpSession) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 63 with FileUploadException

use of org.apache.commons.fileupload.FileUploadException in project opencast by opencast.

the class EventHttpServletRequest method updateFromHttpServletRequest.

/**
 * Load the details of updating an event.
 *
 * @param event
 *          The event to update.
 * @param request
 *          The multipart request that has the data to load the updated event.
 * @param eventCatalogUIAdapters
 *          The list of catalog ui adapters to use to load the event metadata.
 * @param startDatePattern
 *          The pattern to use to parse the start date from the request.
 * @param startTimePattern
 *          The pattern to use to parse the start time from the request.
 * @return The data for the event update
 * @throws IllegalArgumentException
 *           Thrown if the request to update the event is malformed.
 * @throws IndexServiceException
 *           Thrown if something is unable to load the event data.
 * @throws NotFoundException
 *           Thrown if unable to find a metadata catalog or field that matches an input catalog or field.
 */
public static EventHttpServletRequest updateFromHttpServletRequest(Event event, HttpServletRequest request, List<EventCatalogUIAdapter> eventCatalogUIAdapters, Opt<String> startDatePattern, Opt<String> startTimePattern) throws IllegalArgumentException, IndexServiceException, NotFoundException {
    EventHttpServletRequest eventHttpServletRequest = new EventHttpServletRequest();
    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            for (FileItemIterator iter = new ServletFileUpload().getItemIterator(request); iter.hasNext(); ) {
                FileItemStream item = iter.next();
                String fieldName = item.getFieldName();
                if (item.isFormField()) {
                    setFormField(eventCatalogUIAdapters, eventHttpServletRequest, item, fieldName, startDatePattern, startTimePattern);
                }
            }
        } catch (IOException e) {
            throw new IndexServiceException("Unable to update event", e);
        } catch (FileUploadException e) {
            throw new IndexServiceException("Unable to update event", e);
        }
    } else {
        throw new IllegalArgumentException("No multipart content");
    }
    return eventHttpServletRequest;
}
Also used : ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileItemStream(org.apache.commons.fileupload.FileItemStream) IOException(java.io.IOException) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) IndexServiceException(org.opencastproject.index.service.exception.IndexServiceException) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 64 with FileUploadException

use of org.apache.commons.fileupload.FileUploadException 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();
}
Also used : IFactoryApplicationObject(org.cerberus.crud.factory.IFactoryApplicationObject) PolicyFactory(org.owasp.html.PolicyFactory) HashMap(java.util.HashMap) MessageEvent(org.cerberus.engine.entity.MessageEvent) ILogEventService(org.cerberus.crud.service.ILogEventService) LogEventService(org.cerberus.crud.service.impl.LogEventService) Timestamp(java.sql.Timestamp) ApplicationContext(org.springframework.context.ApplicationContext) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) ILogEventService(org.cerberus.crud.service.ILogEventService) IFactoryApplicationObject(org.cerberus.crud.factory.IFactoryApplicationObject) ApplicationObject(org.cerberus.crud.entity.ApplicationObject) IApplicationObjectService(org.cerberus.crud.service.IApplicationObjectService) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) AnswerItem(org.cerberus.util.answer.AnswerItem) FileItemFactory(org.apache.commons.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) Answer(org.cerberus.util.answer.Answer) FileItem(org.apache.commons.fileupload.FileItem) JSONObject(org.json.JSONObject) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 65 with FileUploadException

use of org.apache.commons.fileupload.FileUploadException in project cerberus-source by cerberustesting.

the class importFile method doPost.

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List items = upload.parseRequest(request);
            Iterator iterator = items.iterator();
            File uploadedFile = null;
            String test = "";
            String testcase = "";
            String step = "";
            String load = "";
            while (iterator.hasNext()) {
                FileItem item = (FileItem) iterator.next();
                if (!item.isFormField()) {
                    String fileName = item.getName();
                    String root = getServletContext().getRealPath("/");
                    File pathFile = new File(root + "/cerberusFiles");
                    if (!pathFile.exists()) {
                        // boolean status = pathFile.mkdirs();
                        pathFile.mkdirs();
                    }
                    uploadedFile = new File(pathFile + File.separator + fileName);
                    LOG.debug(uploadedFile.getAbsolutePath());
                    item.write(uploadedFile);
                } else {
                    String name = item.getFieldName();
                    if (name.equals("Test")) {
                        test = item.getString();
                    } else if (name.equals("Testcase")) {
                        testcase = item.getString();
                    } else if (name.equals("Step")) {
                        step = item.getString();
                    } else if (name.equals("Load")) {
                        load = item.getString();
                    }
                }
            }
            response.sendRedirect("ImportHTML.jsp?Test=" + test + "&Testcase=" + testcase + "&Step=" + step + "&Load=" + load + "&FilePath=" + uploadedFile.getAbsolutePath());
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Also used : FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) Iterator(java.util.Iterator) List(java.util.List) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) File(java.io.File) FileItemFactory(org.apache.commons.fileupload.FileItemFactory) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileUploadException(org.apache.commons.fileupload.FileUploadException) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Aggregations

FileUploadException (org.apache.commons.fileupload.FileUploadException)88 ServletFileUpload (org.apache.commons.fileupload.servlet.ServletFileUpload)65 FileItem (org.apache.commons.fileupload.FileItem)57 DiskFileItemFactory (org.apache.commons.fileupload.disk.DiskFileItemFactory)51 IOException (java.io.IOException)37 HashMap (java.util.HashMap)27 ArrayList (java.util.ArrayList)22 List (java.util.List)21 File (java.io.File)20 InputStream (java.io.InputStream)19 FileItemIterator (org.apache.commons.fileupload.FileItemIterator)19 FileItemStream (org.apache.commons.fileupload.FileItemStream)19 FileItemFactory (org.apache.commons.fileupload.FileItemFactory)16 ServletException (javax.servlet.ServletException)12 Map (java.util.Map)9 HttpServletRequest (javax.servlet.http.HttpServletRequest)9 Iterator (java.util.Iterator)8 ApplicationContext (org.springframework.context.ApplicationContext)8 UnsupportedEncodingException (java.io.UnsupportedEncodingException)6 HttpServletResponse (javax.servlet.http.HttpServletResponse)6