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

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

Introduction

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

Prototype

public PortletFileUpload() 

Source Link

Document

Constructs an uninitialised instance of this class.

Usage

From source file:com.serli.chell.framework.upload.FileUploadStatus.java

public static FileUploadStatus fromRequest(ActionRequest request, FormStructure structure) {
    request = new EncodedActionRequest(request);
    FileUploadStatus fus = new FileUploadStatus();
    try {// w ww . j av a  2 s .co  m
        PortletFileUpload upload = new PortletFileUpload();
        FileItemIterator fiit = upload.getItemIterator(request);
        String encoding = request.getCharacterEncoding();
        FormField formField;
        FileItemStream fis;
        String fieldName;
        while (fiit.hasNext()) {
            fis = fiit.next();
            fieldName = fis.getFieldName();
            formField = structure.getField(fieldName);
            if (formField != null) {
                fus.parameterNames.add(fieldName);
                if (fis.isFormField()) {
                    fus.addFormFieldParameter(fis, fieldName, encoding);
                } else {
                    fus.addFileUploadParameter(fis, fieldName, encoding, formField);
                }
            }
        }
        return fus;
    } catch (FileUploadException ex) {
        throw new ChellException("Can not parse upload request.", ex);
    } catch (IOException ex) {
        throw new ChellException("Network error.", ex);
    }
}

From source file:org.apache.myfaces.webapp.filter.PortletMultipartRequestWrapper.java

private void parseRequest() {
    if (cacheFileSizeErrors) {
        fileUpload = new PortletChacheFileSizeErrorsFileUpload();
    } else {//w ww  . j ava  2s. co  m
        fileUpload = new PortletFileUpload();
    }

    fileUpload.setSizeMax(maxSize);
    fileUpload.setFileSizeMax(maxFileSize);

    //fileUpload.setSizeThreshold(thresholdSize);

    if (repositoryPath != null && repositoryPath.trim().length() > 0) {
        //fileUpload.setRepositoryPath(repositoryPath);
        fileUpload.setFileItemFactory(new DiskFileItemFactory(thresholdSize, new File(repositoryPath)));
    } else {
        fileUpload.setFileItemFactory(
                new DiskFileItemFactory(thresholdSize, new File(System.getProperty("java.io.tmpdir"))));
    }

    String charset = request.getCharacterEncoding();
    fileUpload.setHeaderEncoding(charset);

    List requestParameters = null;

    try {
        if (cacheFileSizeErrors) {
            requestParameters = ((PortletChacheFileSizeErrorsFileUpload) fileUpload)
                    .parseRequestCatchingFileSizeErrors(request, fileUpload);
        } else {
            requestParameters = fileUpload.parseRequest(request);
        }
    } catch (FileUploadBase.FileSizeLimitExceededException e) {
        // Since commons-fileupload does not allow to continue processing files
        // if this exception is thrown, we can't do anything else.
        // So, the current request is rejected and we can't restore state, so 
        // this request is dealt like a new request, but note that caching the params
        // below it is possible to detect if the current request has been aborted
        // or not.
        // Note that if cacheFileSizeErrors is true, this is not thrown, so the request
        // is not aborted unless other different error occur.
        request.setAttribute("org.apache.myfaces.custom.fileupload.exception", "fileSizeLimitExceeded");
        request.setAttribute("org.apache.myfaces.custom.fileupload.maxSize", new Integer((int) maxFileSize));

        if (log.isWarnEnabled())
            log.warn("FileSizeLimitExceededException while uploading file.", e);

        requestParameters = Collections.EMPTY_LIST;
    } catch (FileUploadBase.SizeLimitExceededException e) {
        // This exception is thrown when the max request size has been reached.
        // In this case, the current request is rejected. The current 
        // request is dealt like a new request, but note that caching the params below
        // params it is possible to detect if the current request has been aborted
        // or not.
        request.setAttribute("org.apache.myfaces.custom.fileupload.exception", "sizeLimitExceeded");
        request.setAttribute("org.apache.myfaces.custom.fileupload.maxSize", new Integer((int) maxSize));

        if (log.isWarnEnabled())
            log.warn("SizeLimitExceededException while uploading file.", e);

        requestParameters = Collections.EMPTY_LIST;
    } catch (FileUploadException fue) {
        if (log.isErrorEnabled())
            log.error("Exception while uploading file.", fue);

        requestParameters = Collections.EMPTY_LIST;
    }

    parametersMap = new HashMap(requestParameters.size());
    fileItems = new HashMap();

    for (Iterator iter = requestParameters.iterator(); iter.hasNext();) {
        FileItem fileItem = (FileItem) iter.next();

        if (fileItem.isFormField()) {
            String name = fileItem.getFieldName();

            // The following code avoids commons-fileupload charset problem.
            // After fixing commons-fileupload, this code should be
            //
            //     String value = fileItem.getString();
            //
            String value = null;
            if (charset == null) {
                value = fileItem.getString();
            } else {
                try {
                    value = new String(fileItem.get(), charset);
                } catch (UnsupportedEncodingException e) {
                    value = fileItem.getString();
                }
            }

            addTextParameter(name, value);
        } else { // fileItem is a File
            if (fileItem.getName() != null) {
                fileItems.put(fileItem.getFieldName(), fileItem);
            }
        }
    }

    //Add the query string paramters
    for (Iterator it = request.getParameterMap().entrySet().iterator(); it.hasNext();) {
        Map.Entry entry = (Map.Entry) it.next();

        Object value = entry.getValue();

        if (value instanceof String[]) {
            String[] valuesArray = (String[]) entry.getValue();
            for (int i = 0; i < valuesArray.length; i++) {
                addTextParameter((String) entry.getKey(), valuesArray[i]);
            }
        } else if (value instanceof String) {
            String strValue = (String) entry.getValue();
            addTextParameter((String) entry.getKey(), strValue);
        } else if (value != null)
            throw new IllegalStateException("value of type : " + value.getClass() + " for key : "
                    + entry.getKey() + " cannot be handled.");

    }
}

From source file:se.vgregion.portal.innovationsslussen.idea.controller.IdeaViewController.java

/**
 * Upload file action./*from w w w  . j a  v a2 s.c o  m*/
 *
 * @param request  the request
 * @param response the response
 * @param model    the model
 * @throws FileUploadException the file upload exception
 */
@ActionMapping(params = "action=uploadFile")
public void uploadFile(ActionRequest request, ActionResponse response, Model model)
        throws FileUploadException, SystemException, PortalException {

    ThemeDisplay themeDisplay = getThemeDisplay(request);
    long scopeGroupId = themeDisplay.getScopeGroupId();
    long userId = themeDisplay.getUserId();

    String urlTitle = request.getParameter("urlTitle");

    String fileType = request.getParameter("fileType");
    boolean publicIdea;
    if (fileType.equals("public")) {
        publicIdea = true;
    } else if (fileType.equals("private")) {
        publicIdea = false;
    } else {
        throw new IllegalArgumentException("Unknown filetype: " + fileType);
    }

    //TODO ondig slagning? Cacha?
    Idea idea = ideaService.findIdeaByUrlTitle(urlTitle);
    //TODO Kan det inte finnas flera med samma titel i olika communities?

    IdeaContentType ideaContentType = publicIdea ? IdeaContentType.IDEA_CONTENT_TYPE_PUBLIC
            : IdeaContentType.IDEA_CONTENT_TYPE_PRIVATE;

    if (!isAllowedToDoAction(request, idea, Action.UPLOAD_FILE, ideaContentType)) {
        sendRedirectToContextRoot(response);
        return;
    }

    boolean mayUploadFile = idea.getUserId() == userId;

    IdeaPermissionChecker ideaPermissionChecker = ideaPermissionCheckerService
            .getIdeaPermissionChecker(scopeGroupId, userId, idea);

    if (!mayUploadFile) {
        if (publicIdea) {
            mayUploadFile = ideaPermissionChecker.isHasPermissionAddDocumentPublic();
        } else {
            mayUploadFile = ideaPermissionChecker.isHasPermissionAddDocumentPrivate();
        }
    }

    if (mayUploadFile) {
        response.setRenderParameter("urlTitle", urlTitle);

        PortletFileUpload p = new PortletFileUpload();

        try {
            FileItemIterator itemIterator = p.getItemIterator(request);

            while (itemIterator.hasNext()) {
                FileItemStream fileItemStream = itemIterator.next();

                if (fileItemStream.getFieldName().equals("file")) {

                    InputStream is = fileItemStream.openStream();
                    BufferedInputStream bis = new BufferedInputStream(is);

                    String fileName = fileItemStream.getName();
                    String contentType = fileItemStream.getContentType();

                    ideaService.uploadFile(idea, publicIdea, fileName, contentType, bis);
                }
            }
        } catch (FileUploadException e) {
            doExceptionStuff(e, response, model);
            return;
        } catch (IOException e) {
            doExceptionStuff(e, response, model);
            return;
        } catch (se.vgregion.service.innovationsslussen.exception.FileUploadException e) {
            doExceptionStuff(e, response, model);
            return;
        } catch (RuntimeException e) {
            Throwable lastCause = Util.getLastCause(e);
            if (lastCause instanceof SQLException) {
                SQLException nextException = ((SQLException) lastCause).getNextException();
                if (nextException != null) {
                    LOGGER.error(nextException.getMessage(), nextException);
                }
            }
        } finally {
            response.setRenderParameter("ideaType", fileType);
        }
    } else {
        throw new FileUploadException("The user is not authorized to upload to this idea instance.");
    }

    response.setRenderParameter("urlTitle", urlTitle);
    response.setRenderParameter("type", fileType);
    response.setRenderParameter("showView", "showIdea");
}