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

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

Introduction

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

Prototype

public List  parseRequest(ActionRequest request) throws FileUploadException 

Source Link

Document

Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a> compliant <code>multipart/form-data</code> stream.

Usage

From source file:org.gatein.wcm.portlet.editor.views.ManagerActions.java

public String actionNewImport(ActionRequest request, ActionResponse response, UserWcm userWcm) {
    log.info("WCM Import: STARTED");

    String tmpDir = System.getProperty(Wcm.UPLOADS.TMP_DIR);
    FileItemFactory factory = new DiskFileItemFactory(Wcm.UPLOADS.MAX_FILE_SIZE, new File(tmpDir));
    PortletFileUpload importUpload = new PortletFileUpload(factory);
    try {/*from  w  w w .  j  a v a2 s .c om*/
        List<FileItem> items = importUpload.parseRequest(request);
        FileItem file = null;
        String importStrategy = String.valueOf(Wcm.IMPORT.STRATEGY.NEW);
        for (FileItem item : items) {
            if (!item.isFormField()) {
                file = item;
            } else {
                importStrategy = item.getString();
            }
        }
        // .zip validation
        if (file != null && file.getContentType() != null
                && !"application/zip".equalsIgnoreCase(file.getContentType())) {
            throw new WcmException("File: " + file.getName() + " is not application/zip.");
        }
        //
        log.info("Importing ... " + file.getName() + " with strategy " + importStrategy);
        wcm.importRepository(file.getInputStream(), importStrategy.charAt(0), userWcm);
    } catch (Exception e) {
        log.warning("Error importing file");
        e.printStackTrace();
        response.setRenderParameter("errorWcm", "Error importing file: " + e.toString());
    }

    log.info("WCM Import: FINISHED");

    return Wcm.VIEWS.MANAGER;
}

From source file:org.gatein.wcm.portlet.editor.views.UploadsActions.java

public String actionNewUpload(ActionRequest request, ActionResponse response, UserWcm userWcm) {
    String tmpDir = System.getProperty(Wcm.UPLOADS.TMP_DIR);
    FileItemFactory factory = new DiskFileItemFactory(Wcm.UPLOADS.MAX_FILE_SIZE, new File(tmpDir));
    PortletFileUpload upload = new PortletFileUpload(factory);
    try {/*w w w .  j av a2  s . co  m*/
        List<FileItem> items = upload.parseRequest(request);
        FileItem file = null;
        String description = "";
        for (FileItem item : items) {
            if (!item.isFormField()) {
                file = item;
            } else {
                description = item.getString();
            }
        }
        Upload newUpload = new Upload();
        newUpload.setFileName(file.getName());
        newUpload.setMimeType(file.getContentType());
        newUpload.setDescription(description);
        wcm.create(newUpload, file.getInputStream(), userWcm);
        return Wcm.VIEWS.UPLOADS;
    } catch (Exception e) {
        log.warning("Error uploading file");
        e.printStackTrace();
        response.setRenderParameter("errorWcm", "Error uploading file " + e.toString());
    }
    return Wcm.VIEWS.UPLOADS;
}

From source file:org.gatein.wcm.portlet.editor.views.UploadsActions.java

public String actionEditUpload(ActionRequest request, ActionResponse response, UserWcm userWcm) {
    String tmpDir = System.getProperty(Wcm.UPLOADS.TMP_DIR);
    FileItemFactory factory = new DiskFileItemFactory(Wcm.UPLOADS.MAX_FILE_SIZE, new File(tmpDir));
    PortletFileUpload upload = new PortletFileUpload(factory);
    try {//from w  w w . j a v a  2s .  c  o  m
        List<FileItem> items = upload.parseRequest(request);
        FileItem file = null;
        String description = null;
        String editUploadId = null;
        for (FileItem item : items) {
            if (!item.isFormField()) {
                file = item;
            } else {
                if (item.getFieldName().equals("uploadFileDescription")) {
                    description = item.getString();
                } else if (item.getFieldName().equals("editUploadId")) {
                    editUploadId = item.getString();
                }
            }
        }
        Upload updateUpload = wcm.findUpload(new Long(editUploadId), userWcm);
        if (updateUpload != null) {
            if (file != null && file.getSize() > 0 && file.getName().length() > 0) {
                updateUpload.setFileName(file.getName());
                updateUpload.setMimeType(file.getContentType());
                updateUpload.setDescription(description);
                wcm.unlock(new Long(editUploadId), Wcm.LOCK.UPLOAD, userWcm);
                wcm.update(updateUpload, file.getInputStream(), userWcm);
            } else {
                if (description != null) {
                    updateUpload.setDescription(description);
                    wcm.unlock(new Long(editUploadId), Wcm.LOCK.UPLOAD, userWcm);
                    wcm.update(updateUpload, userWcm);
                }
            }
        }
        return Wcm.VIEWS.UPLOADS;
    } catch (Exception e) {
        log.warning("Error uploading file");
        e.printStackTrace();
        response.setRenderParameter("errorWcm", "Error uploading file " + e.toString());
    }
    return Wcm.VIEWS.UPLOADS;
}

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

public File getFile() {
    try {/*from ww  w  . j  av a 2s .c o  m*/
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // Configure the factory here, if desired.
        PortletFileUpload upload = new PortletFileUpload(factory);
        // Configure the uploader here, if desired.
        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 fieldName = dfi.getFieldName();
                String fileName = dfi.getName();
                String contentType = dfi.getContentType();
                boolean isInMemory = dfi.isInMemory();
                long sizeInBytes = dfi.getSize();

                log.debug("fieldName:" + fieldName);
                log.debug("fileName:" + fileName);
                log.debug("contentType:" + contentType);
                log.debug("isInMemory:" + isInMemory);
                log.debug("sizeInBytes:" + sizeInBytes);
                File uploadedFile = new File(getTempFilePath() + File.separator + fileName);
                dfi.write(uploadedFile);
                return uploadedFile;
            }

        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return file;
}

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

/**
 * This is the entry point for the main listing.
 *//*from   w  w  w .  j a  v  a  2s . 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;
}

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

/**
 * This is the entry point for the main listing.
 *//* w ww.  j  a  v  a2s. c  o m*/

public String upload() throws Exception {

    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // Configure the factory here, if desired.
        PortletFileUpload upload = new PortletFileUpload(factory);
        // Configure the uploader here, if desired.
        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 fieldName = dfi.getFieldName();
                String fileName = dfi.getName();
                String contentType = dfi.getContentType();
                boolean isInMemory = dfi.isInMemory();
                long sizeInBytes = dfi.getSize();

                log.debug("fieldName:" + fieldName);
                log.debug("fileName:" + fileName);
                log.debug("contentType:" + contentType);
                log.debug("isInMemory:" + isInMemory);
                log.debug("sizeInBytes:" + sizeInBytes);
                File uploadedFile = new File(getTempFilePath() + File.separator + fileName);
                dfi.write(uploadedFile);
            }

        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    log.debug("");
    ResourceController.getController().createResource(this.eventId, this.getAssetKey(),
            this.getFileContentType(), this.getFileFileName(), this.getFile(), getSession());

    return "successUpload";
}

From source file:org.intalio.tempo.web.AlfrescoFacesPortlet.java

/**
 * Called by the portlet container to allow the portlet to process an action
 * request./*w w w  . j  a  v a 2s  .  com*/
 */
public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException {
    Application.setInPortalServer(true);

    // Set the current locale
    I18NUtil.setLocale(Application.getLanguage(request.getPortletSession()));

    boolean isMultipart = PortletFileUpload.isMultipartContent(request);

    try {
        // NOTE: Due to filters not being called within portlets we can not
        // make use
        // of the MyFaces file upload support, therefore we are using a pure
        // portlet request/action to handle file uploads until there is a
        // solution.

        if (isMultipart) {
            if (logger.isDebugEnabled())
                logger.debug("Handling multipart request...");

            PortletSession session = request.getPortletSession();

            // get the file from the request and put it in the session
            DiskFileItemFactory factory = new DiskFileItemFactory();
            PortletFileUpload upload = new PortletFileUpload(factory);
            List<FileItem> fileItems = upload.parseRequest(request);
            Iterator<FileItem> iter = fileItems.iterator();
            FileUploadBean bean = new FileUploadBean();
            while (iter.hasNext()) {
                FileItem item = iter.next();
                String filename = item.getName();
                if (item.isFormField() == false) {
                    if (logger.isDebugEnabled())
                        logger.debug("Processing uploaded file: " + filename);

                    // workaround a bug in IE where the full path is
                    // returned
                    // IE is only available for Windows so only check for
                    // the Windows path separator
                    int idx = filename.lastIndexOf('\\');

                    if (idx == -1) {
                        // if there is no windows path separator check for
                        // *nix
                        idx = filename.lastIndexOf('/');
                    }

                    if (idx != -1) {
                        filename = filename.substring(idx + File.separator.length());
                    }

                    File tempFile = TempFileProvider.createTempFile("alfresco", ".upload");
                    item.write(tempFile);
                    bean.setFile(tempFile);
                    bean.setFileName(filename);
                    bean.setFilePath(tempFile.getAbsolutePath());
                    session.setAttribute(FileUploadBean.FILE_UPLOAD_BEAN_NAME, bean,
                            PortletSession.PORTLET_SCOPE);
                }
            }

            // Set the VIEW_ID parameter to tell the faces portlet bridge to
            // treat the request
            // as a JSF request, this will send us back to the previous page
            // we came from.
            String lastViewId = (String) request.getPortletSession().getAttribute(SESSION_LAST_VIEW_ID);
            if (lastViewId != null) {
                response.setRenderParameter(VIEW_ID, lastViewId);
            }
        } else {
            User user = (User) request.getPortletSession()
                    .getAttribute(AuthenticationHelper.AUTHENTICATION_USER);
            if (user != null) {
                // setup the authentication context
                try {
                    WebApplicationContext ctx = (WebApplicationContext) getPortletContext()
                            .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
                    AuthenticationService auth = (AuthenticationService) ctx.getBean("AuthenticationService");
                    auth.validate(user.getTicket());

                    // save last username into portlet preferences, get from
                    // LoginBean state
                    LoginBean loginBean = (LoginBean) request.getPortletSession()
                            .getAttribute(AuthenticationHelper.LOGIN_BEAN);
                    if (loginBean != null) {
                        // TODO: Need to login to the Portal to get a user
                        // here to store prefs against
                        // so not really a suitable solution as they get
                        // thrown away at present!
                        // Also would need to store prefs PER user - so auto
                        // login for each...?
                        String oldValue = request.getPreferences().getValue(PREF_ALF_USERNAME, null);
                        if (oldValue == null || oldValue.equals(loginBean.getUsernameInternal()) == false) {
                            if (request.getPreferences().isReadOnly(PREF_ALF_USERNAME) == false) {
                                request.getPreferences().setValue(PREF_ALF_USERNAME,
                                        loginBean.getUsernameInternal());
                                request.getPreferences().store();
                            }
                        }
                    }

                    // do the normal JSF processing
                    super.processAction(request, response);
                } catch (AuthenticationException authErr) {
                    // remove User object as it's now useless
                    request.getPortletSession().removeAttribute(AuthenticationHelper.AUTHENTICATION_USER);
                }
            } else {
                // do the normal JSF processing as we may be on the login
                // page
                super.processAction(request, response);
            }
        }
    } catch (Throwable e) {
        if (getErrorPage() != null) {
            handleError(request, response, e);
        } else {
            logger.warn("No error page configured, re-throwing exception");

            if (e instanceof PortletException) {
                throw (PortletException) e;
            } else if (e instanceof IOException) {
                throw (IOException) e;
            } else {
                throw new PortletException(e);
            }
        }
    }
}

From source file:org.jcrportlet.portlet.JCRPortlet.java

@Override
public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException {
    // TODO Auto-generated method stub
    if (PortletFileUpload.isMultipartContent(request)) {
        FileItemFactory factory = new DiskFileItemFactory();
        PortletFileUpload fu = new PortletFileUpload(factory);
        List<FileItem> list;
        try {//w w  w .  j a  v a  2 s  . c o  m
            FileItem item = null;
            list = fu.parseRequest(request);
            for (FileItem fileItem : list) {
                item = fileItem;
            }

            JCRBrowser jcrBrowser = new JCRBrowser();
            jcrBrowser.connectRepository("repository");

            Node fileNode = jcrBrowser.uploadItem("hehe", item);
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (RepositoryException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (RepositoryConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

From source file:org.logomattic.portlet.LogomatticPortlet.java

@Override
public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException {
    LogomatticContext model = new LogomatticContext(chromattic, request, response);
    try {// w w w  .j  a  v  a  2  s  . c o  m
        if (PortletFileUpload.isMultipartContent(request)) {
            FileItem image = null;
            try {
                FileItemFactory factory = new DiskFileItemFactory();
                PortletFileUpload fu = new PortletFileUpload(factory);
                List<FileItem> list = fu.parseRequest(request);
                for (FileItem item : list) {
                    if (item.getFieldName().equals("uploadedimage")) {
                        if (item.getContentType().startsWith("image/")) {
                            image = item;
                            break;
                        }
                    }
                }
            } catch (FileUploadException e) {
                throw new PortletException("Could not process file upload", e);
            }

            //
            if (image != null) {
                model.save(image);
            }
        } else {
            String action = request.getParameter("action");
            if ("use".equals(action)) {
                String docId = request.getParameter("docid");
                if (docId != null) {
                    PortletPreferences prefs = request.getPreferences();
                    prefs.setValue("url", docId);
                    prefs.store();
                }
            } else if ("remove".equals(action)) {
                String docId = request.getParameter("docid");
                if (docId != null) {
                    PortletPreferences prefs = request.getPreferences();
                    if (docId.equals(prefs.getValue("url", null))) {
                        prefs.reset("url");
                        prefs.store();
                    }

                    //
                    model.remove(docId);
                }
            } else if ("title".equals(action)) {
                String title = request.getParameter("title");
                if (title != null) {
                    PortletPreferences prefs = request.getPreferences();
                    prefs.setValue("title", title);
                    prefs.store();
                }
            }
        }
    } finally {
        model.close();
    }
}

From source file:org.xmlportletfactory.portal.example01.UsersPortlet.java

private ActionRequest extractFields(ActionRequest request, boolean edit) throws FileUploadException {

    FileItemFactory factory = new DiskFileItemFactory();
    PortletFileUpload uploadItems = new PortletFileUpload(factory);
    List<FileItem> allItems = uploadItems.parseRequest(request);
    //Separate formFields <-> fileItems
    for (FileItem item : allItems) {
        String formField = item.getFieldName();
        if (item.isFormField()) {
            //Non-file items
            //Push all to request object
            if (formField.startsWith(UsersUpload.HIDDEN)) {
                uploadManager.addHidden(formField, Long.parseLong(item.getString()));
            } else if (formField.endsWith(UsersUpload.DOCUMENT_DELETE)) {
                int pos = formField.indexOf(UsersUpload.DOCUMENT_DELETE);
                formField = formField.substring(0, pos - 1);
                int pos2 = formField.lastIndexOf(UsersUpload.SEPARATOR);
                formField = formField.substring(pos2 + 1);
                if (item.getString().equals("true"))
                    uploadManager.addDeleted(formField);
            } else {
                int pos = formField.lastIndexOf(UsersUpload.SEPARATOR);
                formField = formField.substring(pos + 1);
                try {
                    request.setAttribute(formField, item.getString("UTF-8").trim());
                } catch (Exception e) {
                }// ww w  . ja v  a2 s .co  m
            }
        } else {
            uploadManager.add(item);
        }
    }
    return request;
}