Example usage for org.apache.commons.fileupload.portlet PortletFileUpload setSizeMax

List of usage examples for org.apache.commons.fileupload.portlet PortletFileUpload setSizeMax

Introduction

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

Prototype

public void setSizeMax(long sizeMax) 

Source Link

Document

Sets the maximum allowed upload size.

Usage

From source file:org.dihedron.strutlets.ActionContext.java

/**
 * Initialise the attributes map used to emulate the per-request attributes;
 * this map will simulate action-scoped request parameters, and will be populated 
 * with attributes that must be visible to all the render, serve resource and 
 * event handling requests coming after an action processing request. These 
 * parameters will be reset by the <code>ActionController</code>as soon as a 
 * new action processing request comes. 
 * /*from ww  w  . j a v a  2s .c  o  m*/
 * @param response
 *   the portlet response.
 * @param invocation
 *   the optional <code>ActionInvocation</code> object, only available in the
 *   context of an action or event processing, not in the render phase.
 * @throws StrutletsException 
 */
static void bindContext(GenericPortlet portlet, PortletRequest request, PortletResponse response,
        Properties configuration, ApplicationServer server, PortalServer portal,
        FileUploadConfiguration uploadInfo) throws StrutletsException {

    logger.debug("initialising the action context for thread {}", Thread.currentThread().getId());

    getContext().portlet = portlet;
    getContext().request = request;
    getContext().response = response;
    getContext().configuration = configuration;
    getContext().server = server;
    getContext().portal = portal;
    getContext().renderParametersChanged = false;

    // check if a map for REQUEST-scoped attributes is already available in
    // the PORTLET, if not instantiate it and load it into PORTLET scope
    PortletSession session = request.getPortletSession();
    @SuppressWarnings("unchecked")
    Map<String, Object> map = (Map<String, Object>) session.getAttribute(getRequestScopedAttributesKey(),
            PortletSession.PORTLET_SCOPE);
    if (map == null) {
        logger.trace("installing REQUEST scoped attributes map into PORTLET scope");
        session.setAttribute(getRequestScopedAttributesKey(), new HashMap<String, Object>(),
                PortletSession.PORTLET_SCOPE);
    }

    // this might be a multipart/form-data request, in which case we enable
    // support for file uploads and read them from the input stream using
    // a tweaked version of Apache Commons FileUpload facilities (in order 
    // to support file uploads in AJAX requests too!).
    if (request instanceof ClientDataRequest) {

        // this is where we try to retrieve all files (if there are any that were 
        // uploaded) and store them as temporary files on disk; these objects will
        // be accessible as ordinary values under the "FORM" scope through a 
        // custom "filename-to-file" map, which will be clened up when the context
        // is unbound
        String encoding = ((ClientDataRequest) request).getCharacterEncoding();
        getContext().encoding = Strings.isValid(encoding) ? encoding : DEFAULT_ENCODING;
        logger.trace("request encoding is: '{}'", getContext().encoding);

        try {
            RequestContext context = new ClientDataRequestContext((ClientDataRequest) request);

            // check that we have a file upload request
            if (PortletFileUpload.isMultipartContent(context)) {

                getContext().parts = new HashMap<String, FileItem>();

                logger.trace("handling multipart/form-data request");

                // create a factory for disk-based file items
                DiskFileItemFactory factory = new DiskFileItemFactory();

                // register a tracker to perform automatic file cleanup
                //                 FileCleaningTracker tracker = FileCleanerCleanup.getFileCleaningTracker(getContext().filter.getServletContext());
                //                 factory.setFileCleaningTracker(tracker);

                // configure the repository (to ensure a secure temporary location 
                // is used and the size of the )
                factory.setRepository(uploadInfo.getRepository());
                factory.setSizeThreshold(uploadInfo.getInMemorySizeThreshold());

                // create a new file upload handler
                PortletFileUpload upload = new PortletFileUpload(factory);
                upload.setSizeMax(uploadInfo.getMaxUploadableTotalSize());
                upload.setFileSizeMax(uploadInfo.getMaxUploadableFileSize());

                // parse the request & process the uploaded items
                List<FileItem> items = upload.parseRequest(context);
                logger.trace("{} items in the multipart/form-data request", items.size());
                for (FileItem item : items) {
                    // parameters would be stored with their fully-qualified 
                    // name if we didn't remove the portlet namespace
                    String fieldName = item.getFieldName().replaceFirst(getPortletNamespace(), "");
                    logger.trace("storing field '{}' (type: '{}') into parts map", fieldName,
                            item.isFormField() ? "field" : "file");
                    getContext().parts.put(fieldName, item);
                }
            } else {
                logger.trace("handling plain form request");
            }
        } catch (FileUploadException e) {
            logger.warn("error handling uploaded file", e);
            throw new StrutletsException("Error handling uploaded file", e);
        }
    }
}

From source file:org.infoglue.calendar.actions.CreateResourceAction.java

/**
 * This is the entry point for the main listing.
 *//*from ww w.ja  v a 2  s  . c om*/

public String execute() throws Exception {
    log.debug("-------------Uploading file.....");

    File uploadedFile = null;
    String maxUploadSize = "";
    String uploadSize = "";

    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(2000000);
        //factory.setRepository(yourTempDirectory);

        PortletFileUpload upload = new PortletFileUpload(factory);

        String maxSize = getSetting("AssetUploadMaxFileSize");
        log.debug("maxSize:" + maxSize);
        if (maxSize != null && !maxSize.equals("") && !maxSize.equals("@AssetUploadMaxFileSize@")) {
            try {
                maxUploadSize = maxSize;
                upload.setSizeMax((new Long(maxSize) * 1000));
            } catch (Exception e) {
                log.warn("Faulty max size parameter sent from portlet component:" + maxSize);
            }
        } else {
            maxSize = "" + (10 * 1024);
            maxUploadSize = maxSize;
            upload.setSizeMax((new Long(maxSize) * 1000));
        }

        List fileItems = upload.parseRequest(ServletActionContext.getRequest());
        log.debug("fileItems:" + fileItems.size());
        Iterator i = fileItems.iterator();
        while (i.hasNext()) {
            Object o = i.next();
            DiskFileItem dfi = (DiskFileItem) o;
            log.debug("dfi:" + dfi.getFieldName());
            log.debug("dfi:" + dfi);

            if (dfi.isFormField()) {
                String name = dfi.getFieldName();
                String value = dfi.getString();
                uploadSize = "" + (dfi.getSize() / 1000);

                log.debug("name:" + name);
                log.debug("value:" + value);
                if (name.equals("assetKey")) {
                    this.assetKey = value;
                } else if (name.equals("eventId")) {
                    this.eventId = new Long(value);
                    ServletActionContext.getRequest().setAttribute("eventId", this.eventId);
                } else if (name.equals("calendarId")) {
                    this.calendarId = new Long(value);
                    ServletActionContext.getRequest().setAttribute("calendarId", this.calendarId);
                } else if (name.equals("mode"))
                    this.mode = value;
            } else {
                String fieldName = dfi.getFieldName();
                String fileName = dfi.getName();
                uploadSize = "" + (dfi.getSize() / 1000);

                this.fileName = fileName;
                log.debug("FileName:" + this.fileName);
                uploadedFile = new File(getTempFilePath() + File.separator + fileName);
                dfi.write(uploadedFile);
            }

        }
    } catch (Exception e) {
        ServletActionContext.getRequest().getSession().setAttribute("errorMessage",
                "Exception uploading resource. " + e.getMessage() + ".<br/>Max upload size: " + maxUploadSize
                        + " KB"); // + "<br/>Attempted upload size (in KB):" + uploadSize);
        ActionContext.getContext().getValueStack().getContext().put("errorMessage",
                "Exception uploading resource. " + e.getMessage() + ".<br/>Max upload size: " + maxUploadSize
                        + " KB"); // + "<br/>Attempted upload size (in KB):" + uploadSize);
        log.error("Exception uploading resource. " + e.getMessage());
        return Action.ERROR;
    }

    try {
        log.debug("Creating resources.....:" + this.eventId + ":"
                + ServletActionContext.getRequest().getParameter("eventId") + ":"
                + ServletActionContext.getRequest().getParameter("calendarId"));
        ResourceController.getController().createResource(this.eventId, this.getAssetKey(),
                this.getFileContentType(), this.getFileName(), uploadedFile, getSession());
    } catch (Exception e) {
        ServletActionContext.getRequest().getSession().setAttribute("errorMessage",
                "Exception saving resource to database: " + e.getMessage());
        ActionContext.getContext().getValueStack().getContext().put("errorMessage",
                "Exception saving resource to database: " + e.getMessage());
        log.error("Exception saving resource to database. " + e.getMessage());
        return Action.ERROR;
    }

    return Action.SUCCESS;
}