Example usage for org.apache.commons.fileupload.servlet ServletFileUpload setSizeMax

List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload setSizeMax

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.servlet ServletFileUpload setSizeMax.

Prototype

public void setSizeMax(long sizeMax) 

Source Link

Document

Sets the maximum allowed upload size.

Usage

From source file:nl.armatiek.xslweb.serializer.RequestSerializer.java

private List<FileItem> getMultipartContentItems() throws IOException, FileUploadException {
    List<FileItem> items = null;
    boolean isMultipart = ServletFileUpload.isMultipartContent(req);
    if (isMultipart) {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(0);/*  www  .  j av a 2  s  .c  o m*/
        reposDir = new File(FileUtils.getTempDirectory(), File.separatorChar + UUID.randomUUID().toString());
        if (!reposDir.mkdirs()) {
            throw new XSLWebException(
                    String.format("Could not create DiskFileItemFactory repository directory (%s)",
                            reposDir.getAbsolutePath()));
        }
        factory.setRepository(reposDir);
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(1024 * 1024 * webApp.getMaxUploadSize());
        items = upload.parseRequest(req);
    }
    return items;
}

From source file:nl.b3p.commons.uploadProgress.ExtendedMultipartRequestHandler.java

/**
 * Parses the input stream and partitions the parsed items into a set of
 * form fields and a set of file items. In the process, the parsed items
 * are translated from Commons FileUpload <code>FileItem</code> instances
 * to Struts <code>FormFile</code> instances.
 *
 * @param request The multipart request to be processed.
 *
 * @throws ServletException if an unrecoverable error occurs.
 *///w w  w  .  j  a  v a  2s  . co  m
public void handleRequest(HttpServletRequest request) throws ServletException {
    // Get the app config for the current request.
    ModuleConfig ac = (ModuleConfig) request.getAttribute(Globals.MODULE_KEY);

    // Create and configure a DIskFileUpload instance.
    //everything thats added:
    UploadListener listener = new UploadListener(request, 1);
    FileItemFactory factory = new MonitoredDiskFileItemFactory(listener);
    ServletFileUpload upload = new ServletFileUpload(factory);

    // The following line is to support an "EncodingFilter"
    // see http://nagoya.apache.org/bugzilla/show_bug.cgi?id=23255
    upload.setHeaderEncoding(request.getCharacterEncoding());
    // Set the maximum size before a FileUploadException will be thrown.
    upload.setSizeMax(getSizeMax(ac));
    // Set the maximum size that will be stored in memory.
    //upload.setSizeThreshold((int) getSizeThreshold(ac));
    // Set the the location for saving data on disk.
    //upload.setRepositoryPath(getRepositoryPath(ac));

    // Create the hash tables to be populated.
    elementsText = new Hashtable();
    elementsFile = new Hashtable();
    elementsAll = new Hashtable();

    // Parse the request into file items.
    List items = null;
    try {
        items = upload.parseRequest(request);
    } catch (DiskFileUpload.SizeLimitExceededException e) {
        // Special handling for uploads that are too big.
        request.setAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED, Boolean.TRUE);
        return;
    } catch (FileUploadException e) {
        log.error("Failed to parse multipart request", e);
        throw new ServletException(e);
    }

    // Partition the items into form fields and files.
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (item.isFormField()) {
            addTextParameter(request, item);
        } else {
            addFileParameter(item);
        }
    }
}

From source file:nl.fontys.pts61a.vps.controller.UploadController.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (!ServletFileUpload.isMultipartContent(request)) {
        PrintWriter writer = response.getWriter();
        writer.println("Error: Form must has enctype=multipart/form-data.");
        writer.flush();/*from  w  ww  .  jav a  2s .  c o m*/
        return;
    }

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(MEMORY_THRESHOLD);
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(MAX_REQUEST_SIZE);
    String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;

    File uploadDir = new File("verplaatsingen");
    if (!uploadDir.exists()) {
        uploadDir.mkdir();
    }

    try {
        @SuppressWarnings("unchecked")
        List<FileItem> formItems = upload.parseRequest(request);

        if (formItems != null && formItems.size() > 0) {
            for (FileItem item : formItems) {
                if (!item.isFormField()) {

                    final InputStream stream = item.getInputStream();
                    final byte[] bytes = IOUtils.toByteArray(stream);
                    String movementJson = new String(bytes, "UTF-8");

                    String fileName = new File(item.getName()).getName();
                    String filePath = uploadPath + File.separator + fileName;
                    File storeFile = new File(filePath);

                    JSONObject json = (JSONObject) new JSONParser().parse(movementJson);
                    Long cartrackerId = Long.parseLong(json.get("cartrackerId").toString());

                    String verificatieCode = json.get("verificatieCode").toString();

                    Cartracker c = service.checkCartrackerId(cartrackerId, verificatieCode);
                    Long nextId = c.getLastId() + 1l;

                    if (Objects.equals(nextId, Long.valueOf(json.get("currentId").toString()))) {

                        List<JSONObject> movementsJson = (List<JSONObject>) json.get("verplaatsingen");

                        for (JSONObject jo : movementsJson) {
                            Movement m = new Movement();
                            m.setLongitude(Double.parseDouble(jo.get("longitude").toString()));
                            m.setLatitude(Double.parseDouble(jo.get("latitude").toString()));
                            String string = jo.get("date").toString();

                            java.util.Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(string);
                            new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(date);
                            m.setRegistrationDate(date);
                            m.setMovementId(Long.parseLong(jo.get("movementId").toString()));
                            m.setDistance(Long.parseLong(jo.get("distance").toString()));
                            m.setCartracker(c);
                            service.addMovement(m);
                        }
                        service.setCartracketNextId(c, nextId);
                    } else {
                        PrintWriter writer = response.getWriter();
                        writer.println("Missing: " + nextId);
                        writer.flush();
                        return;
                    }
                    //                        try {
                    //                            item.write(storeFile);
                    //                        } catch (Exception ex) {
                    //                            Logger.getLogger(UploadController.class.getName()).log(Level.SEVERE, null, ex);
                    //                        }

                }
            }

            PrintWriter writer = response.getWriter();
            writer.println("File uploaded.");
            writer.flush();
        }
    } catch (ParseException | FileUploadException | java.text.ParseException ex) {
        Logger.getLogger(UploadController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:nu.kelvin.jfileshare.ajax.FileReceiverServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    HttpSession session = req.getSession();
    UserItem currentUser = (UserItem) session.getAttribute("user");
    if (currentUser != null && ServletFileUpload.isMultipartContent(req)) {
        Conf conf = (Conf) getServletContext().getAttribute("conf");
        // keep files of up to 10 MiB in memory 10485760
        FileItemFactory factory = new DiskFileItemFactory(10485760, new File(conf.getPathTemp()));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(conf.getFileSizeMax());

        // set file upload progress listener
        FileUploadListener listener = new FileUploadListener();
        session.setAttribute("uploadListener", listener);
        upload.setProgressListener(listener);

        File tempFile = File.createTempFile(String.format("%05d-", currentUser.getUid()), null,
                new File(conf.getPathTemp()));
        tempFile.deleteOnExit();/*w w  w .  ja v  a  2  s .c  o m*/
        try {
            FileItem file = new FileItem();

            /* iterate over all uploaded items */
            FileItemIterator it = upload.getItemIterator(req);
            FileOutputStream filestream = null;

            while (it.hasNext()) {
                FileItemStream item = it.next();
                String name = item.getFieldName();
                InputStream instream = item.openStream();
                DigestOutputStream outstream = null;

                if (item.isFormField()) {
                    String value = Streams.asString(instream);
                    // logger.info(name + " : " + value);
                    /* not the file upload. Maybe the password field? */
                    if (name.equals("password") && !value.equals("")) {
                        logger.info("Uploaded file has password set");
                        file.setPwPlainText(value);
                    }
                    instream.close();
                } else {
                    // This is the file you're looking for
                    file.setName(item.getName());
                    file.setType(
                            item.getContentType() == null ? "application/octet-stream" : item.getContentType());
                    file.setUid(currentUser.getUid());

                    try {
                        filestream = new FileOutputStream(tempFile);
                        MessageDigest md = MessageDigest.getInstance("MD5");
                        outstream = new DigestOutputStream(filestream, md);
                        long filesize = IOUtils.copyLarge(instream, outstream);

                        if (filesize == 0) {
                            throw new Exception("File is empty.");
                        }
                        md = outstream.getMessageDigest();
                        file.setMd5sum(toHex(md.digest()));
                        file.setSize(filesize);

                    } finally {
                        if (outstream != null) {
                            try {
                                outstream.close();
                            } catch (IOException ignored) {
                            }
                        }
                        if (filestream != null) {
                            try {
                                filestream.close();
                            } catch (IOException ignored) {
                            }
                        }
                        if (instream != null) {
                            try {
                                instream.close();
                            } catch (IOException ignored) {
                            }
                        }
                    }
                }
            }
            /* All done. Save the new file */
            if (conf.getDaysFileExpiration() != 0) {
                file.setDaysToKeep(conf.getDaysFileExpiration());
            }
            if (file.create(ds, req.getRemoteAddr())) {
                File finalFile = new File(conf.getPathStore(), Integer.toString(file.getFid()));
                tempFile.renameTo(finalFile);
                logger.log(Level.INFO, "User {0} storing file \"{1}\" in the filestore",
                        new Object[] { currentUser.getUid(), file.getName() });
                req.setAttribute("msg",
                        "File <strong>\"" + Helpers.htmlSafe(file.getName())
                                + "\"</strong> uploaded successfully. <a href='" + req.getContextPath()
                                + "/file/edit/" + file.getFid() + "'>Click here to edit file</a>");
                req.setAttribute("javascript", "parent.uploadComplete('info');");
            } else {
                req.setAttribute("msg", "Unable to contact the database");
                req.setAttribute("javascript", "parent.uploadComplete('critical');");
            }
        } catch (SizeLimitExceededException e) {
            tempFile.delete();
            req.setAttribute("msg", "File is too large. The maximum size of file uploads is "
                    + FileItem.humanReadable(conf.getFileSizeMax()));
            req.setAttribute("javascript", "parent.uploadComplete('warning');");
        } catch (FileUploadException e) {
            tempFile.delete();
            req.setAttribute("msg", "Unable to upload file");
            req.setAttribute("javascript", "parent.uploadComplete('warning');");
        } catch (Exception e) {
            tempFile.delete();
            req.setAttribute("msg",
                    "Unable to upload file. ".concat(e.getMessage() == null ? "" : e.getMessage()));
            req.setAttribute("javascript", "parent.uploadComplete('warning');");
        } finally {
            session.setAttribute("uploadListener", null);
        }
        ServletContext app = getServletContext();
        RequestDispatcher disp = app.getRequestDispatcher("/templates/AjaxDummy.jsp");
        disp.forward(req, resp);
    }
}

From source file:onlinefrontlines.utils.UploadedImageManager.java

/**
 * Add image from http request/*from   w w  w . j  a va 2s .c  o m*/
 * 
 * @param prefix Prefix for the image
 * @param id Id for the image
 * @param request Request that contains the image data
 * @param width Max with for the image
 * @param height Max height for the image
 * @throws AddException
 */
@SuppressWarnings("unchecked")
public void addImage(String prefix, int id, HttpServletRequest request, int width, int height)
        throws AddException {
    try {
        // Get files from request
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(MAX_FILE_SIZE);
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(MAX_FILE_SIZE);
        List<FileItem> items = (List<FileItem>) upload.parseRequest(request);

        // Find correct attachment
        for (FileItem item : items)
            if (!item.isFormField()) {
                // Skip file uploads that don't have a file name - meaning that no file was selected.
                if (item.getName() == null || item.getName().trim().length() < 1)
                    continue;

                try {
                    // Read image to see if it is correct
                    InputStream is = item.getInputStream();
                    try {
                        BufferedImage image = ImageIO.read(is);
                        if (image == null)
                            throw new AddException("imageCorrupt");
                        if (image.getHeight() != height || image.getWidth() != width)
                            throw new AddException("invalidResolution");
                    } finally {
                        is.close();
                    }

                    // Add the image
                    is = item.getInputStream();
                    try {
                        addImage(prefix, id, is, item.getContentType());
                    } finally {
                        is.close();
                    }
                    break;
                } catch (IOException e) {
                    throw new AddException("imageCorrupt");
                }
            }
    } catch (FileUploadException e) {
        throw new AddException("failedFileUpload");
    }
}

From source file:org.apache.felix.webconsole.AbstractWebConsolePluginServlet.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public static String getRequestParameter(HttpServletRequest request, String name) {
    // just get the parameter if not a multipart/form-data POST
    if (!ServletFileUpload.isMultipartContent(new ServletRequestContext(request))) {
        return request.getParameter(name);
    }//from  w w  w  .  j  ava  2 s  . c o  m

    // check, whether we alread have the parameters
    Map params = (Map) request.getAttribute(ATTR_FILEUPLOAD);
    if (params == null) {
        // parameters not read yet, read now
        // Create a factory for disk-based file items
        DiskFileItemFactory myFactory = new DiskFileItemFactory();
        myFactory.setSizeThreshold(FACTORY_LIMIT);

        // Create a new file upload handler
        ServletFileUpload uploadServlet = new ServletFileUpload(myFactory);
        uploadServlet.setSizeMax(-1);

        // Parse the request
        params = new HashMap();
        try {
            List parseItems = uploadServlet.parseRequest(request);
            for (Iterator fIter = parseItems.iterator(); fIter.hasNext();) {
                FileItem fileItem = (FileItem) fIter.next();
                FileItem[] currentItem = (FileItem[]) params.get(fileItem.getFieldName());
                if (currentItem == null) {
                    currentItem = new FileItem[] { fileItem };
                } else {
                    FileItem[] newCurrent = new FileItem[currentItem.length + 1];
                    System.arraycopy(currentItem, 0, newCurrent, 0, currentItem.length);
                    newCurrent[currentItem.length] = fileItem;
                    currentItem = newCurrent;
                }
                params.put(fileItem.getFieldName(), currentItem);
            }
        } catch (FileUploadException fue) {
        }
        request.setAttribute(ATTR_FILEUPLOAD, params);
    }

    FileItem[] fileParam = (FileItem[]) params.get(name);
    if (fileParam != null) {
        for (int i = 0; i < fileParam.length; i++) {
            if (fileParam[i].isFormField()) {
                return fileParam[i].getString();
            }
        }
    }

    // no valid string parameter, fail
    return null;
}

From source file:org.apache.felix.webconsole.WebConsoleUtil.java

/**
 * An utility method, that is used to filter out simple parameter from file
 * parameter when multipart transfer encoding is used.
 *
 * This method processes the request and sets a request attribute
 * {@link AbstractWebConsolePlugin#ATTR_FILEUPLOAD}. The attribute value is a {@link Map}
 * where the key is a String specifying the field name and the value
 * is a {@link org.apache.commons.fileupload.FileItem}.
 *
 * @param request the HTTP request coming from the user
 * @param name the name of the parameter
 * @return if not multipart transfer encoding is used - the value is the
 *  parameter value or <code>null</code> if not set. If multipart is used,
 *  and the specified parameter is field - then the value of the parameter
 *  is returned./*from  w  w  w . j a v  a  2 s . c  om*/
 */
public static final String getParameter(HttpServletRequest request, String name) {
    // just get the parameter if not a multipart/form-data POST
    if (!FileUploadBase.isMultipartContent(new ServletRequestContext(request))) {
        return request.getParameter(name);
    }

    // check, whether we already have the parameters
    Map params = (Map) request.getAttribute(AbstractWebConsolePlugin.ATTR_FILEUPLOAD);
    if (params == null) {
        // parameters not read yet, read now
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(256000);

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(-1);

        // Parse the request
        params = new HashMap();
        try {
            List items = upload.parseRequest(request);
            for (Iterator fiter = items.iterator(); fiter.hasNext();) {
                FileItem fi = (FileItem) fiter.next();
                FileItem[] current = (FileItem[]) params.get(fi.getFieldName());
                if (current == null) {
                    current = new FileItem[] { fi };
                } else {
                    FileItem[] newCurrent = new FileItem[current.length + 1];
                    System.arraycopy(current, 0, newCurrent, 0, current.length);
                    newCurrent[current.length] = fi;
                    current = newCurrent;
                }
                params.put(fi.getFieldName(), current);
            }
        } catch (FileUploadException fue) {
            // TODO: log
        }
        request.setAttribute(AbstractWebConsolePlugin.ATTR_FILEUPLOAD, params);
    }

    FileItem[] param = (FileItem[]) params.get(name);
    if (param != null) {
        for (int i = 0; i < param.length; i++) {
            if (param[i].isFormField()) {
                return param[i].getString();
            }
        }
    }

    // no valid string parameter, fail
    return null;
}

From source file:org.apache.ofbiz.webapp.event.ServiceEventHandler.java

/**
 * @see org.apache.ofbiz.webapp.event.EventHandler#invoke(ConfigXMLReader.Event, ConfigXMLReader.RequestMap, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//*from  w  w w.  j  a  v  a 2 s .c om*/
public String invoke(Event event, RequestMap requestMap, HttpServletRequest request,
        HttpServletResponse response) throws EventHandlerException {
    // make sure we have a valid reference to the Service Engine
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    if (dispatcher == null) {
        throw new EventHandlerException("The local service dispatcher is null");
    }
    DispatchContext dctx = dispatcher.getDispatchContext();
    if (dctx == null) {
        throw new EventHandlerException("Dispatch context cannot be found");
    }

    // get the details for the service(s) to call
    String mode = SYNC;
    String serviceName = null;

    if (UtilValidate.isEmpty(event.path)) {
        mode = SYNC;
    } else {
        mode = event.path;
    }

    // make sure we have a defined service to call
    serviceName = event.invoke;
    if (serviceName == null) {
        throw new EventHandlerException("Service name (eventMethod) cannot be null");
    }
    if (Debug.verboseOn())
        Debug.logVerbose("[Set mode/service]: " + mode + "/" + serviceName, module);

    // some needed info for when running the service
    Locale locale = UtilHttp.getLocale(request);
    TimeZone timeZone = UtilHttp.getTimeZone(request);
    HttpSession session = request.getSession();
    GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");

    // get the service model to generate context
    ModelService model = null;

    try {
        model = dctx.getModelService(serviceName);
    } catch (GenericServiceException e) {
        throw new EventHandlerException("Problems getting the service model", e);
    }

    if (model == null) {
        throw new EventHandlerException("Problems getting the service model");
    }

    if (Debug.verboseOn()) {
        Debug.logVerbose("[Processing]: SERVICE Event", module);
        Debug.logVerbose("[Using delegator]: " + dispatcher.getDelegator().getDelegatorName(), module);
    }

    boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
    Map<String, Object> multiPartMap = new HashMap<String, Object>();
    if (isMultiPart) {
        // get the http upload configuration
        String maxSizeStr = EntityUtilProperties.getPropertyValue("general", "http.upload.max.size", "-1",
                dctx.getDelegator());
        long maxUploadSize = -1;
        try {
            maxUploadSize = Long.parseLong(maxSizeStr);
        } catch (NumberFormatException e) {
            Debug.logError(e, "Unable to obtain the max upload size from general.properties; using default -1",
                    module);
            maxUploadSize = -1;
        }
        // get the http size threshold configuration - files bigger than this will be
        // temporarly stored on disk during upload
        String sizeThresholdStr = EntityUtilProperties.getPropertyValue("general",
                "http.upload.max.sizethreshold", "10240", dctx.getDelegator());
        int sizeThreshold = 10240; // 10K
        try {
            sizeThreshold = Integer.parseInt(sizeThresholdStr);
        } catch (NumberFormatException e) {
            Debug.logError(e, "Unable to obtain the threshold size from general.properties; using default 10K",
                    module);
            sizeThreshold = -1;
        }
        // directory used to temporarily store files that are larger than the configured size threshold
        String tmpUploadRepository = EntityUtilProperties.getPropertyValue("general",
                "http.upload.tmprepository", "runtime/tmp", dctx.getDelegator());
        String encoding = request.getCharacterEncoding();
        // check for multipart content types which may have uploaded items

        ServletFileUpload upload = new ServletFileUpload(
                new DiskFileItemFactory(sizeThreshold, new File(tmpUploadRepository)));

        // create the progress listener and add it to the session
        FileUploadProgressListener listener = new FileUploadProgressListener();
        upload.setProgressListener(listener);
        session.setAttribute("uploadProgressListener", listener);

        if (encoding != null) {
            upload.setHeaderEncoding(encoding);
        }
        upload.setSizeMax(maxUploadSize);

        List<FileItem> uploadedItems = null;
        try {
            uploadedItems = UtilGenerics.<FileItem>checkList(upload.parseRequest(request));
        } catch (FileUploadException e) {
            throw new EventHandlerException("Problems reading uploaded data", e);
        }
        if (uploadedItems != null) {
            for (FileItem item : uploadedItems) {
                String fieldName = item.getFieldName();
                //byte[] itemBytes = item.get();
                /*
                Debug.logInfo("Item Info [" + fieldName + "] : " + item.getName() + " / " + item.getSize() + " / " +
                    item.getContentType() + " FF: " + item.isFormField(), module);
                */
                if (item.isFormField() || item.getName() == null) {
                    if (multiPartMap.containsKey(fieldName)) {
                        Object mapValue = multiPartMap.get(fieldName);
                        if (mapValue instanceof List<?>) {
                            checkList(mapValue, Object.class).add(item.getString());
                        } else if (mapValue instanceof String) {
                            List<String> newList = new LinkedList<String>();
                            newList.add((String) mapValue);
                            newList.add(item.getString());
                            multiPartMap.put(fieldName, newList);
                        } else {
                            Debug.logWarning("Form field found [" + fieldName + "] which was not handled!",
                                    module);
                        }
                    } else {
                        if (encoding != null) {
                            try {
                                multiPartMap.put(fieldName, item.getString(encoding));
                            } catch (java.io.UnsupportedEncodingException uee) {
                                Debug.logError(uee, "Unsupported Encoding, using deafault", module);
                                multiPartMap.put(fieldName, item.getString());
                            }
                        } else {
                            multiPartMap.put(fieldName, item.getString());
                        }
                    }
                } else {
                    String fileName = item.getName();
                    if (fileName.indexOf('\\') > -1 || fileName.indexOf('/') > -1) {
                        // get just the file name IE and other browsers also pass in the local path
                        int lastIndex = fileName.lastIndexOf('\\');
                        if (lastIndex == -1) {
                            lastIndex = fileName.lastIndexOf('/');
                        }
                        if (lastIndex > -1) {
                            fileName = fileName.substring(lastIndex + 1);
                        }
                    }
                    multiPartMap.put(fieldName, ByteBuffer.wrap(item.get()));
                    multiPartMap.put("_" + fieldName + "_size", Long.valueOf(item.getSize()));
                    multiPartMap.put("_" + fieldName + "_fileName", fileName);
                    multiPartMap.put("_" + fieldName + "_contentType", item.getContentType());
                }
            }
        }
    }

    // store the multi-part map as an attribute so we can access the parameters
    request.setAttribute("multiPartMap", multiPartMap);

    Map<String, Object> rawParametersMap = UtilHttp.getCombinedMap(request);
    Set<String> urlOnlyParameterNames = UtilHttp.getUrlOnlyParameterMap(request).keySet();

    // we have a service and the model; build the context
    Map<String, Object> serviceContext = new HashMap<String, Object>();
    for (ModelParam modelParam : model.getInModelParamList()) {
        String name = modelParam.name;

        // don't include userLogin, that's taken care of below
        if ("userLogin".equals(name))
            continue;
        // don't include locale, that is also taken care of below
        if ("locale".equals(name))
            continue;
        // don't include timeZone, that is also taken care of below
        if ("timeZone".equals(name))
            continue;

        Object value = null;
        if (UtilValidate.isNotEmpty(modelParam.stringMapPrefix)) {
            Map<String, Object> paramMap = UtilHttp.makeParamMapWithPrefix(request, multiPartMap,
                    modelParam.stringMapPrefix, null);
            value = paramMap;
            if (Debug.verboseOn())
                Debug.logVerbose("Set [" + modelParam.name + "]: " + paramMap, module);
        } else if (UtilValidate.isNotEmpty(modelParam.stringListSuffix)) {
            List<Object> paramList = UtilHttp.makeParamListWithSuffix(request, multiPartMap,
                    modelParam.stringListSuffix, null);
            value = paramList;
        } else {
            // first check the multi-part map
            value = multiPartMap.get(name);

            // next check attributes; do this before parameters so that attribute which can be changed by code can override parameters which can't
            if (UtilValidate.isEmpty(value)) {
                Object tempVal = request
                        .getAttribute(UtilValidate.isEmpty(modelParam.requestAttributeName) ? name
                                : modelParam.requestAttributeName);
                if (tempVal != null) {
                    value = tempVal;
                }
            }

            // check the request parameters
            if (UtilValidate.isEmpty(value)) {
                ServiceEventHandler.checkSecureParameter(requestMap, urlOnlyParameterNames, name, session,
                        serviceName, dctx.getDelegator());

                // if the service modelParam has allow-html="any" then get this direct from the request instead of in the parameters Map so there will be no canonicalization possibly messing things up
                if ("any".equals(modelParam.allowHtml)) {
                    value = request.getParameter(name);
                } else {
                    // use the rawParametersMap from UtilHttp in order to also get pathInfo parameters, do canonicalization, etc
                    value = rawParametersMap.get(name);
                }

                // make any composite parameter data (e.g., from a set of parameters {name_c_date, name_c_hour, name_c_minutes})
                if (value == null) {
                    value = UtilHttp.makeParamValueFromComposite(request, name, locale);
                }
            }

            // then session
            if (UtilValidate.isEmpty(value)) {
                Object tempVal = request.getSession()
                        .getAttribute(UtilValidate.isEmpty(modelParam.sessionAttributeName) ? name
                                : modelParam.sessionAttributeName);
                if (tempVal != null) {
                    value = tempVal;
                }
            }

            // no field found
            if (value == null) {
                //still null, give up for this one
                continue;
            }

            if (value instanceof String && ((String) value).length() == 0) {
                // interpreting empty fields as null values for each in back end handling...
                value = null;
            }
        }
        // set even if null so that values will get nulled in the db later on
        serviceContext.put(name, value);
    }

    // get only the parameters for this service - converted to proper type
    // TODO: pass in a list for error messages, like could not convert type or not a proper X, return immediately with messages if there are any
    List<Object> errorMessages = new LinkedList<Object>();
    serviceContext = model.makeValid(serviceContext, ModelService.IN_PARAM, true, errorMessages, timeZone,
            locale);
    if (errorMessages.size() > 0) {
        // uh-oh, had some problems...
        request.setAttribute("_ERROR_MESSAGE_LIST_", errorMessages);
        return "error";
    }

    // include the UserLogin value object
    if (userLogin != null) {
        serviceContext.put("userLogin", userLogin);
    }

    // include the Locale object
    if (locale != null) {
        serviceContext.put("locale", locale);
    }

    // include the TimeZone object
    if (timeZone != null) {
        serviceContext.put("timeZone", timeZone);
    }

    // invoke the service
    Map<String, Object> result = null;
    try {
        if (ASYNC.equalsIgnoreCase(mode)) {
            dispatcher.runAsync(serviceName, serviceContext);
        } else {
            result = dispatcher.runSync(serviceName, serviceContext);
        }
    } catch (ServiceAuthException e) {
        // not logging since the service engine already did
        request.setAttribute("_ERROR_MESSAGE_", e.getNonNestedMessage());
        return "error";
    } catch (ServiceValidationException e) {
        // not logging since the service engine already did
        request.setAttribute("serviceValidationException", e);
        if (e.getMessageList() != null) {
            request.setAttribute("_ERROR_MESSAGE_LIST_", e.getMessageList());
        } else {
            request.setAttribute("_ERROR_MESSAGE_", e.getNonNestedMessage());
        }
        return "error";
    } catch (GenericServiceException e) {
        Debug.logError(e, "Service invocation error", module);
        throw new EventHandlerException("Service invocation error", e.getNested());
    }

    String responseString = null;

    if (result == null) {
        responseString = ModelService.RESPOND_SUCCESS;
    } else {

        if (!result.containsKey(ModelService.RESPONSE_MESSAGE)) {
            responseString = ModelService.RESPOND_SUCCESS;
        } else {
            responseString = (String) result.get(ModelService.RESPONSE_MESSAGE);
        }

        // set the messages in the request; this will be picked up by messages.ftl and displayed
        request.setAttribute("_ERROR_MESSAGE_LIST_", result.get(ModelService.ERROR_MESSAGE_LIST));
        request.setAttribute("_ERROR_MESSAGE_MAP_", result.get(ModelService.ERROR_MESSAGE_MAP));
        request.setAttribute("_ERROR_MESSAGE_", result.get(ModelService.ERROR_MESSAGE));

        request.setAttribute("_EVENT_MESSAGE_LIST_", result.get(ModelService.SUCCESS_MESSAGE_LIST));
        request.setAttribute("_EVENT_MESSAGE_", result.get(ModelService.SUCCESS_MESSAGE));

        // set the results in the request
        for (Map.Entry<String, Object> rme : result.entrySet()) {
            String resultKey = rme.getKey();
            Object resultValue = rme.getValue();

            if (resultKey != null && !ModelService.RESPONSE_MESSAGE.equals(resultKey)
                    && !ModelService.ERROR_MESSAGE.equals(resultKey)
                    && !ModelService.ERROR_MESSAGE_LIST.equals(resultKey)
                    && !ModelService.ERROR_MESSAGE_MAP.equals(resultKey)
                    && !ModelService.SUCCESS_MESSAGE.equals(resultKey)
                    && !ModelService.SUCCESS_MESSAGE_LIST.equals(resultKey)) {
                request.setAttribute(resultKey, resultValue);
            }
        }
    }

    if (Debug.verboseOn())
        Debug.logVerbose("[Event Return]: " + responseString, module);
    return responseString;
}

From source file:org.apache.sling.engine.impl.parameters.ParameterSupport.java

private void parseMultiPartPost(ParameterMap parameters) {

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();
    upload.setSizeMax(ParameterSupport.maxRequestSize);
    upload.setFileSizeMax(ParameterSupport.maxFileSize);
    upload.setFileItemFactory(/*  w  w w  .  j a v  a 2  s  .c om*/
            new DiskFileItemFactory(ParameterSupport.fileSizeThreshold, ParameterSupport.location));

    RequestContext rc = new ServletRequestContext(this.getServletRequest()) {
        @Override
        public String getCharacterEncoding() {
            String enc = super.getCharacterEncoding();
            return (enc != null) ? enc : Util.ENCODING_DIRECT;
        }
    };

    // Parse the request
    List<?> /* FileItem */ items = null;
    try {
        items = upload.parseRequest(rc);
    } catch (FileUploadException fue) {
        this.log.error("parseMultiPartPost: Error parsing request", fue);
    }

    if (items != null && items.size() > 0) {
        for (Iterator<?> ii = items.iterator(); ii.hasNext();) {
            FileItem fileItem = (FileItem) ii.next();
            RequestParameter pp = new MultipartRequestParameter(fileItem);
            parameters.addParameter(pp, false);
        }
    }
}

From source file:org.apache.sling.osgi.obr.OSGiBundleRepositoryServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    // check whether dumping the repository is requested
    if (req.getRequestURI().endsWith("/repository.zip")) {
        this.dumpRepository(req.getParameterValues("bundle"), resp);
        resp.sendRedirect(req.getRequestURI());
        return;//from  w  w w.  ja  va2  s.co m
    }

    if (!ServletFileUpload.isMultipartContent(new ServletRequestContext(req))) {
        resp.sendRedirect(req.getRequestURI());
        return;
    }

    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(256000);

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(-1);

    // Parse the request
    boolean noRedirect = false;
    String bundleLocation = null;
    InputStream bundleStream = null;
    try {
        List /* FileItem */ items = upload.parseRequest(req);

        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            if (!item.isFormField()) {
                bundleStream = item.getInputStream();
                bundleLocation = item.getName();
            } else {
                noRedirect |= "_noredir_".equals(item.getFieldName());
            }
        }

        if (bundleStream != null && bundleLocation != null) {
            try {
                this.repository.addResource(bundleStream);
            } catch (IOException ioe) {
                resp.sendError(500, "Cannot register file " + bundleLocation + ". Reason: " + ioe.getMessage());
            }

        }
    } catch (FileUploadException fue) {
        throw new ServletException(fue.getMessage(), fue);
    } finally {
        if (bundleStream != null) {
            try {
                bundleStream.close();
            } catch (IOException ignore) {
            }
        }
    }

    // only redirect if not instructed otherwise
    if (noRedirect) {
        resp.setContentType("text/plain");
        if (bundleLocation != null) {
            resp.getWriter().print("Bundle " + bundleLocation + " uploaded");
        } else {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            resp.getWriter().print("No Bundle uploaded");
        }
    } else {
        resp.sendRedirect(req.getRequestURI());
    }
}