Example usage for org.apache.commons.fileupload FileItem getString

List of usage examples for org.apache.commons.fileupload FileItem getString

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem getString.

Prototype

String getString(String encoding) throws UnsupportedEncodingException;

Source Link

Document

Returns the contents of the file item as a String, using the specified encoding.

Usage

From source file:dk.clarin.tools.rest.register.java

public String getargs(HttpServletRequest request, List<FileItem> items) {
    String arg = "";
    /*//from  w  w w . j a  v  a 2  s .c o  m
    * Parse the request
    */

    @SuppressWarnings("unchecked")
    Enumeration<String> parmNames = (Enumeration<String>) request.getParameterNames();
    boolean is_multipart_formData = ServletFileUpload.isMultipartContent(request);

    logger.debug("is_multipart_formData:" + (is_multipart_formData ? "ja" : "nej"));

    if (is_multipart_formData) {
        try {
            Iterator<FileItem> itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                if (item.isFormField()) {
                    arg = arg + " (" + workflow.quote(item.getFieldName()) + "."
                            + workflow.quote(item.getString("UTF-8").trim()) + ")";
                }
            }
        } catch (Exception ex) {
            logger.error("uploadHandler.parseRequest Exception");
        }
    }

    for (Enumeration<String> e = parmNames; e.hasMoreElements();) {
        String parmName = e.nextElement();
        arg = arg + " (" + workflow.quote(parmName) + ".";
        String vals[] = request.getParameterValues(parmName);
        for (int j = 0; j < vals.length; ++j) {
            arg += " " + workflow.quote(vals[j]) + "";
        }
        arg += ")";
    }
    logger.debug("arg = [" + arg + "]");
    return arg;
}

From source file:com.silverpeas.form.AbstractFormTest.java

@Test
public void testIsEmptyWithAllFileItemsWithoutContent() throws Exception {
    MyFormImpl myForm = new MyFormImpl(
            new MyRecordTemplate(new MyFieldTemplate(FIELD_NAME1, FIELD_TYPE, FIELD_LABEL1),
                    new MyFieldTemplate(FIELD_NAME2, FIELD_TYPE, FIELD_LABEL2)));
    DataRecord dataRecord = mock(DataRecord.class);
    PagesContext pagesContext = mock(PagesContext.class);
    FileItem fileItem1 = mock(FileItem.class);
    when(fileItem1.getFieldName()).thenReturn(FIELD_NAME1);
    when(fileItem1.getName()).thenReturn(FIELD_NAME1);
    when(fileItem1.isFormField()).thenReturn(true);
    when(fileItem1.getString(anyString())).thenReturn("");
    FileItem fileItem2 = mock(FileItem.class);
    when(fileItem2.getFieldName()).thenReturn(FIELD_NAME2);
    when(fileItem2.getName()).thenReturn(FIELD_NAME2);
    when(fileItem2.isFormField()).thenReturn(true);
    when(fileItem2.getString(anyString())).thenReturn(null);
    boolean isEmpty = myForm.isEmpty(Arrays.asList(fileItem1, fileItem2), dataRecord, pagesContext);
    assertTrue(isEmpty);//w w w. j  a va 2 s  .  com
}

From source file:com.silverpeas.form.AbstractFormTest.java

@Test
public void testIsNotEmptyWithOnlyOneFileItemWithoutContent() throws Exception {
    MyFormImpl myForm = new MyFormImpl(
            new MyRecordTemplate(new MyFieldTemplate(FIELD_NAME1, FIELD_TYPE, FIELD_LABEL1),
                    new MyFieldTemplate(FIELD_NAME2, FIELD_TYPE, FIELD_LABEL2)));
    DataRecord dataRecord = mock(DataRecord.class);
    PagesContext pagesContext = mock(PagesContext.class);
    FileItem fileItem1 = mock(FileItem.class);
    when(fileItem1.getFieldName()).thenReturn(FIELD_NAME1);
    when(fileItem1.getName()).thenReturn(FIELD_NAME1);
    when(fileItem1.isFormField()).thenReturn(true);
    when(fileItem1.getString(anyString())).thenReturn("tartempion");
    FileItem fileItem2 = mock(FileItem.class);
    when(fileItem2.getFieldName()).thenReturn(FIELD_NAME2);
    when(fileItem2.getName()).thenReturn(FIELD_NAME2);
    when(fileItem2.isFormField()).thenReturn(true);
    when(fileItem2.getString(anyString())).thenReturn(null);
    boolean isEmpty = myForm.isEmpty(Arrays.asList(fileItem1, fileItem2), dataRecord, pagesContext);
    assertFalse(isEmpty);/*ww w.j a va2  s  .co m*/
}

From source file:cn.clxy.studio.common.web.multipart.GFileUploadSupport.java

/**
 * Parse the given List of Commons FileItems into a Spring MultipartParsingResult, containing Spring MultipartFile
 * instances and a Map of multipart parameter.
 *
 * @param fileItems the Commons FileIterms to parse
 * @param encoding the encoding to use for form fields
 * @return the Spring MultipartParsingResult
 * @see GMultipartFile#CommonsMultipartFile(org.apache.commons.fileupload.FileItem)
 *//*from   w  w  w .j  av  a 2  s. c o  m*/
protected MultipartParsingResult parseFileItems(List<FileItem> fileItems, String encoding) {
    MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<String, MultipartFile>();
    Map<String, String[]> multipartParameters = new HashMap<String, String[]>();
    Map<String, String> multipartParameterContentTypes = new HashMap<String, String>();

    // Extract multipart files and multipart parameters.
    for (FileItem fileItem : fileItems) {
        if (fileItem.isFormField()) {
            String value = null;
            if (encoding != null) {
                try {
                    value = fileItem.getString(encoding);
                } catch (UnsupportedEncodingException ex) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Could not decode multipart item '" + fileItem.getFieldName()
                                + "' with encoding '" + encoding + "': using platform default");
                    }
                    value = fileItem.getString();
                }
            } else {
                value = fileItem.getString();
            }
            String[] curParam = multipartParameters.get(fileItem.getFieldName());
            if (curParam == null) {
                // simple form field
                multipartParameters.put(fileItem.getFieldName(), new String[] { value });
            } else {
                // array of simple form fields
                String[] newParam = StringUtils.addStringToArray(curParam, value);
                multipartParameters.put(fileItem.getFieldName(), newParam);
            }
            multipartParameterContentTypes.put(fileItem.getFieldName(), fileItem.getContentType());
        } else {
            // multipart file field
            GMultipartFile file = new GMultipartFile(fileItem);
            multipartFiles.add(file.getName(), file);
            if (logger.isDebugEnabled()) {
                logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize()
                        + " bytes with original filename [" + file.getOriginalFilename() + "], stored "
                        + file.getStorageDescription());
            }
        }
    }
    return new MultipartParsingResult(multipartFiles, multipartParameters, multipartParameterContentTypes);
}

From source file:ex.fileupload.spring.GFileUploadSupport.java

/**
 * Parse the given List of Commons FileItems into a Spring
 * MultipartParsingResult, containing Spring MultipartFile instances and a
 * Map of multipart parameter./*from w w  w  . j a va 2 s  .  c  om*/
 * 
 * @param fileItems
 *            the Commons FileIterms to parse
 * @param encoding
 *            the encoding to use for form fields
 * @return the Spring MultipartParsingResult
 * @see GMultipartFile#CommonsMultipartFile(org.apache.commons.fileupload.FileItem)
 */
protected MultipartParsingResult parseFileItems(List<FileItem> fileItems, String encoding) {
    MultiValueMap<String, MultipartFile> multipartFiles = new LinkedMultiValueMap<String, MultipartFile>();
    Map<String, String[]> multipartParameters = new HashMap<String, String[]>();
    Map<String, String> multipartParameterContentTypes = new HashMap<String, String>();

    // Extract multipart files and multipart parameters.
    for (FileItem fileItem : fileItems) {
        if (fileItem.isFormField()) {
            String value = null;
            if (encoding != null) {
                try {
                    value = fileItem.getString(encoding);
                } catch (UnsupportedEncodingException ex) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Could not decode multipart item '" + fileItem.getFieldName()
                                + "' with encoding '" + encoding + "': using platform default");
                    }
                    value = fileItem.getString();
                }
            } else {
                value = fileItem.getString();
            }
            String[] curParam = multipartParameters.get(fileItem.getFieldName());
            if (curParam == null) {
                // simple form field
                multipartParameters.put(fileItem.getFieldName(), new String[] { value });
            } else {
                // array of simple form fields
                String[] newParam = StringUtils.addStringToArray(curParam, value);
                multipartParameters.put(fileItem.getFieldName(), newParam);
            }
            multipartParameterContentTypes.put(fileItem.getName(), fileItem.getContentType());
        } else {
            // multipart file field
            GMultipartFile file = new GMultipartFile(fileItem);
            multipartFiles.add(file.getName(), file);
            if (logger.isDebugEnabled()) {
                logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize()
                        + " bytes with original filename [" + file.getOriginalFilename() + "], stored "
                        + file.getStorageDescription());
            }
        }
    }
    return new MultipartParsingResult(multipartFiles, multipartParameters, multipartParameterContentTypes);
}

From source file:com.ikon.servlet.admin.MimeTypeServlet.java

@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    String action = WebUtils.getString(request, "action");
    String userId = request.getRemoteUser();
    Session dbSession = null;//from w  ww .ja v  a 2s  .  co m
    updateSessionManager(request);

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            InputStream is = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            MimeType mt = new MimeType();
            byte data[] = null;

            for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem item = it.next();

                if (item.isFormField()) {
                    if (item.getFieldName().equals("action")) {
                        action = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("mt_id")) {
                        mt.setId(Integer.parseInt(item.getString("UTF-8")));
                    } else if (item.getFieldName().equals("mt_name")) {
                        mt.setName(item.getString("UTF-8").toLowerCase());
                    } else if (item.getFieldName().equals("mt_extensions")) {
                        String[] extensions = item.getString("UTF-8").split(" ");
                        for (int i = 0; i < extensions.length; i++) {
                            mt.getExtensions().add(extensions[i].toLowerCase());
                        }
                    }
                } else {
                    is = item.getInputStream();
                    data = IOUtils.toByteArray(is);
                    mt.setImageMime(MimeTypeConfig.mimeTypes.getContentType(item.getName()));
                    is.close();
                }
            }

            if (action.equals("create")) {
                // Because this servlet is also used for SQL import and in that case I don't
                // want to waste a b64Encode conversion. Call it a sort of optimization.
                mt.setImageContent(SecureStore.b64Encode(data));
                long id = MimeTypeDAO.create(mt);
                MimeTypeConfig.loadMimeTypes();

                // Activity log
                UserActivity.log(userId, "ADMIN_MIME_TYPE_CREATE", Long.toString(id), null, mt.toString());
                list(userId, request, response);
            } else if (action.equals("edit")) {
                // Because this servlet is also used for SQL import and in that case I don't
                // want to waste a b64Encode conversion. Call it a sort of optimization.
                mt.setImageContent(SecureStore.b64Encode(data));
                MimeTypeDAO.update(mt);
                MimeTypeConfig.loadMimeTypes();

                // Activity log
                UserActivity.log(userId, "ADMIN_MIME_TYPE_EDIT", Long.toString(mt.getId()), null,
                        mt.toString());
                list(userId, request, response);
            } else if (action.equals("delete")) {
                MimeTypeDAO.delete(mt.getId());
                MimeTypeConfig.loadMimeTypes();

                // Activity log
                UserActivity.log(userId, "ADMIN_MIME_TYPE_DELETE", Long.toString(mt.getId()), null, null);
                list(userId, request, response);
            } else if (action.equals("import")) {
                dbSession = HibernateUtil.getSessionFactory().openSession();
                importMimeTypes(userId, request, response, data, dbSession);
                list(userId, request, response);
            }
        }
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (FileUploadException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (SQLException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } finally {
        HibernateUtil.close(dbSession);
    }
}

From source file:com.exedio.cope.live.Bar.java

void doRequest(final HttpServletRequest request, final HttpSession httpSession,
        final HttpServletResponse response, final Anchor anchor) throws IOException {
    if (!Cop.isPost(request)) {
        try {//from   w w  w .  ja va2s . com
            startTransaction("redirectHome");
            anchor.redirectHome(request, response);
            model.commit();
        } finally {
            model.rollbackIfNotCommitted();
        }
        return;
    }

    final String referer;

    if (isMultipartContent(request)) {
        final HashMap<String, String> fields = new HashMap<String, String>();
        final HashMap<String, FileItem> files = new HashMap<String, FileItem>();
        final FileItemFactory factory = new DiskFileItemFactory();
        final ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding(UTF_8.name());
        try {
            for (final Iterator<?> i = upload.parseRequest(request).iterator(); i.hasNext();) {
                final FileItem item = (FileItem) i.next();
                if (item.isFormField())
                    fields.put(item.getFieldName(), item.getString(UTF_8.name()));
                else
                    files.put(item.getFieldName(), item);
            }
        } catch (final FileUploadException e) {
            throw new RuntimeException(e);
        }

        final String featureID = fields.get(FEATURE);
        if (featureID == null)
            throw new NullPointerException();

        final Media feature = (Media) model.getFeature(featureID);
        if (feature == null)
            throw new NullPointerException(featureID);

        final String itemID = fields.get(ITEM);
        if (itemID == null)
            throw new NullPointerException();

        final FileItem file = files.get(FILE);

        try {
            startTransaction("publishFile(" + featureID + ',' + itemID + ')');

            final Item item = model.getItem(itemID);

            if (fields.get(PUBLISH_NOW) != null) {
                for (final History history : History.getHistories(item.getCopeType())) {
                    final History.Event event = history.createEvent(item, anchor.getHistoryAuthor(), false);
                    event.createFeature(feature, feature.getName(),
                            feature.isNull(item) ? null
                                    : ("file type=" + feature.getContentType(item) + " size="
                                            + feature.getLength(item)),
                            "file name=" + file.getName() + " type=" + file.getContentType() + " size="
                                    + file.getSize());
                }

                // TODO use more efficient setter with File or byte[]
                feature.set(item, file.getInputStream(), file.getContentType());
            } else {
                anchor.modify(file, feature, item);
            }

            model.commit();
        } catch (final NoSuchIDException e) {
            throw new RuntimeException(e);
        } finally {
            model.rollbackIfNotCommitted();
        }

        referer = fields.get(REFERER);
    } else // isMultipartContent
    {
        if (request.getParameter(BORDERS_ON) != null || request.getParameter(BORDERS_ON_IMAGE) != null) {
            anchor.borders = true;
        } else if (request.getParameter(BORDERS_OFF) != null
                || request.getParameter(BORDERS_OFF_IMAGE) != null) {
            anchor.borders = false;
        } else if (request.getParameter(CLOSE) != null || request.getParameter(CLOSE_IMAGE) != null) {
            httpSession.removeAttribute(LoginServlet.ANCHOR);
        } else if (request.getParameter(SWITCH_TARGET) != null) {
            anchor.setTarget(servlet.getTarget(request.getParameter(SWITCH_TARGET)));
        } else if (request.getParameter(SAVE_TARGET) != null) {
            try {
                startTransaction("saveTarget");
                anchor.getTarget().save(anchor);
                model.commit();
            } finally {
                model.rollbackIfNotCommitted();
            }
            anchor.notifyPublishedAll();
        } else {
            final String featureID = request.getParameter(FEATURE);
            if (featureID == null)
                throw new NullPointerException();

            final Feature featureO = model.getFeature(featureID);
            if (featureO == null)
                throw new NullPointerException(featureID);

            final String itemID = request.getParameter(ITEM);
            if (itemID == null)
                throw new NullPointerException();

            if (featureO instanceof StringField) {
                final StringField feature = (StringField) featureO;
                final String value = request.getParameter(TEXT);

                try {
                    startTransaction("barText(" + featureID + ',' + itemID + ')');

                    final Item item = model.getItem(itemID);

                    if (request.getParameter(PUBLISH_NOW) != null) {
                        String v = value;
                        if ("".equals(v))
                            v = null;
                        for (final History history : History.getHistories(item.getCopeType())) {
                            final History.Event event = history.createEvent(item, anchor.getHistoryAuthor(),
                                    false);
                            event.createFeature(feature, feature.getName(), feature.get(item), v);
                        }
                        feature.set(item, v);
                        anchor.notifyPublished(feature, item);
                    } else {
                        anchor.modify(value, feature, item);
                    }

                    model.commit();
                } catch (final NoSuchIDException e) {
                    throw new RuntimeException(e);
                } finally {
                    model.rollbackIfNotCommitted();
                }
            } else {
                final IntegerField feature = (IntegerField) featureO;
                final String itemIDFrom = request.getParameter(ITEM_FROM);
                if (itemIDFrom == null)
                    throw new NullPointerException();

                try {
                    startTransaction("swapPosition(" + featureID + ',' + itemIDFrom + ',' + itemID + ')');

                    final Item itemFrom = model.getItem(itemIDFrom);
                    final Item itemTo = model.getItem(itemID);

                    final Integer positionFrom = feature.get(itemFrom);
                    final Integer positionTo = feature.get(itemTo);
                    feature.set(itemFrom, feature.getMinimum());
                    feature.set(itemTo, positionFrom);
                    feature.set(itemFrom, positionTo);

                    for (final History history : History.getHistories(itemFrom.getCopeType())) {
                        final History.Event event = history.createEvent(itemFrom, anchor.getHistoryAuthor(),
                                false);
                        event.createFeature(feature, feature.getName(), positionFrom, positionTo);
                    }
                    for (final History history : History.getHistories(itemTo.getCopeType())) {
                        final History.Event event = history.createEvent(itemTo, anchor.getHistoryAuthor(),
                                false);
                        event.createFeature(feature, feature.getName(), positionTo, positionFrom);
                    }

                    model.commit();
                } catch (final NoSuchIDException e) {
                    throw new RuntimeException(e);
                } finally {
                    model.rollbackIfNotCommitted();
                }
            }
        }

        referer = request.getParameter(REFERER);
    }

    if (referer != null)
        response.sendRedirect(response.encodeRedirectURL(referer));
}

From source file:com.openkm.servlet.admin.MimeTypeServlet.java

@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    String action = WebUtils.getString(request, "action");
    String userId = request.getRemoteUser();
    Session dbSession = null;/*from  w ww.j a  v a 2  s  . c om*/
    updateSessionManager(request);

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            InputStream is = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            MimeType mt = new MimeType();
            byte data[] = null;

            for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
                FileItem item = it.next();

                if (item.isFormField()) {
                    if (item.getFieldName().equals("action")) {
                        action = item.getString("UTF-8");
                    } else if (item.getFieldName().equals("mt_id")) {
                        mt.setId(Integer.parseInt(item.getString("UTF-8")));
                    } else if (item.getFieldName().equals("mt_name")) {
                        mt.setName(item.getString("UTF-8").toLowerCase());
                    } else if (item.getFieldName().equals("mt_description")) {
                        mt.setDescription(item.getString("UTF-8").toLowerCase());
                    } else if (item.getFieldName().equals("mt_search")) {
                        mt.setSearch(true);
                    } else if (item.getFieldName().equals("mt_extensions")) {
                        String[] extensions = item.getString("UTF-8").split(" ");

                        for (int i = 0; i < extensions.length; i++) {
                            mt.getExtensions().add(extensions[i].toLowerCase());
                        }
                    }
                } else {
                    is = item.getInputStream();
                    data = IOUtils.toByteArray(is);
                    mt.setImageMime(MimeTypeConfig.mimeTypes.getContentType(item.getName()));
                    is.close();
                }
            }

            if (action.equals("create")) {
                // Because this servlet is also used for SQL import and in that case I don't
                // want to waste a b64Encode conversion. Call it a sort of optimization.
                mt.setImageContent(SecureStore.b64Encode(data));
                long id = MimeTypeDAO.create(mt);
                MimeTypeConfig.loadMimeTypes();

                // Activity log
                UserActivity.log(userId, "ADMIN_MIME_TYPE_CREATE", Long.toString(id), null, mt.toString());
                list(userId, request, response);
            } else if (action.equals("edit")) {
                // Because this servlet is also used for SQL import and in that case I don't
                // want to waste a b64Encode conversion. Call it a sort of optimization.
                mt.setImageContent(SecureStore.b64Encode(data));
                MimeTypeDAO.update(mt);
                MimeTypeConfig.loadMimeTypes();

                // Activity log
                UserActivity.log(userId, "ADMIN_MIME_TYPE_EDIT", Long.toString(mt.getId()), null,
                        mt.toString());
                list(userId, request, response);
            } else if (action.equals("delete")) {
                MimeTypeDAO.delete(mt.getId());
                MimeTypeConfig.loadMimeTypes();

                // Activity log
                UserActivity.log(userId, "ADMIN_MIME_TYPE_DELETE", Long.toString(mt.getId()), null, null);
                list(userId, request, response);
            } else if (action.equals("import")) {
                dbSession = HibernateUtil.getSessionFactory().openSession();
                importMimeTypes(userId, request, response, data, dbSession);
                list(userId, request, response);
            }
        }
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (FileUploadException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (SQLException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } finally {
        HibernateUtil.close(dbSession);
    }
}

From source file:com.edgenius.wiki.webapp.servlet.UploadServlet.java

@SuppressWarnings("unchecked")
protected void doService(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if ("GET".equalsIgnoreCase(request.getMethod())) {
        //just render blank page for upload
        String pageUuid = request.getParameter("puuid");
        String spaceUname = request.getParameter("uname");
        String draft = request.getParameter("draft");

        request.setAttribute("pageUuid", pageUuid);
        request.setAttribute("spaceUname", spaceUname);
        request.setAttribute("draft", NumberUtils.toInt(draft, PageType.NONE_DRAFT.value()));

        request.getRequestDispatcher("/WEB-INF/pages/upload.jsp").forward(request, response);

        return;// w  ww .ja v a 2s. c  om
    }

    //post - upload

    //      if(WikiUtil.getUser().isAnonymous()){
    //      //anonymous can not allow to upload any files

    PageService pageService = getPageService();

    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());

    List<FileNode> files = new ArrayList<FileNode>();
    String pageUuid = null, spaceUname = null;
    try {
        int status = PageType.NONE_DRAFT.value();
        // index->filename
        Map<String, FileItem> fileMap = new HashMap<String, FileItem>();
        Map<String, String> descMap = new HashMap<String, String>();
        // index->index
        Map<String, String> indexMap = new HashMap<String, String>();

        //offline submission, filename put into hidden variable rather than <input type="file> tag
        Map<String, String> filenameMap = new HashMap<String, String>();
        //TODO: offline submission, version also upload together with file, this give a change to do failure tolerance check:
        //if version is same with online save, then it is OK, if greater, means it maybe duplicated upload, if less, unpexected case
        Map<String, String> versionMap = new HashMap<String, String>();

        Map<String, Boolean> bulkMap = new HashMap<String, Boolean>();

        Map<String, Boolean> sharedMap = new HashMap<String, Boolean>();
        List<FileItem> items = upload.parseRequest(request);
        for (FileItem item : items) {
            String name = item.getFieldName();
            if (StringUtils.equals(name, "spaceUname")) {
                spaceUname = item.getString(Constants.UTF8);
            } else if (StringUtils.equals(name, "pageUuid")) {
                pageUuid = item.getString();
            } else if (name.startsWith("draft")) {
                // check this upload is from "click save button" or "auto upload in draft status"
                status = Integer.parseInt(item.getString());
            } else if (name.startsWith("file")) {
                fileMap.put(name.substring(4), item);
                indexMap.put(name.substring(4), name.substring(4));
            } else if (name.startsWith("desc")) {
                descMap.put(name.substring(4), item.getString(Constants.UTF8));
            } else if (name.startsWith("shar")) {
                sharedMap.put(name.substring(4), Boolean.parseBoolean(item.getString()));
            } else if (name.startsWith("name")) {
                filenameMap.put(name.substring(4), item.getString());
            } else if (name.startsWith("vers")) {
                versionMap.put(name.substring(4), item.getString());
            } else if (name.startsWith("bulk")) {
                bulkMap.put(name.substring(4), BooleanUtils.toBoolean(item.getString()));
            }
        }
        if (StringUtils.isBlank(pageUuid)) {
            log.error("Attachment can not be load because of page does not save successfully.");
            throw new PageException("Attachment can not be load because of page does not save successfully.");
        }

        List<FileNode> bulkFiles = new ArrayList<FileNode>();
        String username = request.getRemoteUser();
        // put file/desc pair into final Map
        for (String id : fileMap.keySet()) {
            FileItem item = fileMap.get(id);
            if (item == null || item.getInputStream() == null || item.getSize() <= 0) {
                log.warn("Empty upload item:" + (item != null ? item.getName() : ""));
                continue;
            }
            FileNode node = new FileNode();
            node.setComment(descMap.get(id));
            node.setShared(sharedMap.get(id) == null ? false : sharedMap.get(id));
            node.setFile(item.getInputStream());
            String filename = item.getName();
            if (StringUtils.isBlank(filename)) {
                //this could be offline submission, get name from map
                filename = filenameMap.get(id);
            }
            node.setFilename(FileUtil.getFileName(filename));
            node.setContentType(item.getContentType());
            node.setIndex(indexMap.get(id));
            node.setType(RepositoryService.TYPE_ATTACHMENT);
            node.setIdentifier(pageUuid);
            node.setCreateor(username);
            node.setStatus(status);
            node.setSize(item.getSize());
            node.setBulkZip(bulkMap.get(id) == null ? false : bulkMap.get(id));

            files.add(node);

            if (node.isBulkZip())
                bulkFiles.add(node);
        }
        if (spaceUname != null && pageUuid != null && files.size() > 0) {
            files = pageService.uploadAttachments(spaceUname, pageUuid, files, false);

            //only save non-draft uploaded attachment
            if (status == 0) {
                try {
                    getActivityLog().logAttachmentUploaded(spaceUname,
                            pageService.getCurrentPageByUuid(pageUuid).getTitle(), WikiUtil.getUser(), files);
                } catch (Exception e) {
                    log.warn("Activity log save error for attachment upload", e);
                }
            }
            //as bulk files won't in return list in PageService.uploadAttachments(), here need 
            //append to all return list, but only for client side "uploading panel" clean purpose
            files.addAll(bulkFiles);
            //TODO: if version come in together, then do check
            //            if(versionMap.size() > 0){
            //               for (FileNode node: files) {
            //                  
            //               }
            //            }
        }

    } catch (RepositoryQuotaException e) {
        FileNode att = new FileNode();
        att.setError(getMessageService().getMessage("err.quota.exhaust"));
        files = Arrays.asList(att);
    } catch (AuthenticationException e) {
        String redir = ((RedirectResponseWrapper) response).getRedirect();
        if (redir == null)
            redir = WikiConstants.URL_LOGIN;
        log.info("Send Authentication redirect URL " + redir);

        FileNode att = new FileNode();
        att.setError(getMessageService().getMessage("err.authentication.required"));
        files = Arrays.asList(att);

    } catch (AccessDeniedException e) {
        String redir = ((RedirectResponseWrapper) response).getRedirect();
        if (redir == null)
            redir = WikiConstants.URL_ACCESS_DENIED;
        log.info("Send AccessDenied redirect URL " + redir);

        FileNode att = new FileNode();
        att.setError(getMessageService().getMessage("err.access.denied"));
        files = Arrays.asList(att);

    } catch (Exception e) {
        // FileUploadException,RepositoryException
        log.error("File upload failed ", e);
        FileNode att = new FileNode();
        att.setError(getMessageService().getMessage("err.upload"));
        files = Arrays.asList(att);
    }

    try {
        String json = FileNode.toAttachmentsJson(files, spaceUname, WikiUtil.getUser(), getMessageService(),
                getUserReadingService());

        //TODO: does not compress request in Gzip, refer to 
        //http://www.google.com/codesearch?hl=en&q=+RemoteServiceServlet+show:PAbNFg2Qpdo:akEoB_bGF1c:4aNSrXYgYQ4&sa=N&cd=1&ct=rc&cs_p=https://ssl.shinobun.org/svn/repos/trunk&cs_f=proprietary/gwt/gwt-user/src/main/java/com/google/gwt/user/server/rpc/RemoteServiceServlet.java#first
        byte[] reply = json.getBytes(Constants.UTF8);
        response.setContentLength(reply.length);
        response.setContentType("text/plain; charset=utf-8");
        response.getOutputStream().write(reply);
    } catch (IOException e) {
        log.error(e.toString(), e);
    }
}

From source file:com.silverpeas.attachment.servlets.DragAndDrop.java

/**
 * Method declaration// w  ww .ja v  a 2s  .  c  o m
 * @param req
 * @param res
 * @throws IOException
 * @throws ServletException
 * @see
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_ENTER_METHOD");
    if (!FileUploadUtil.isRequestMultipart(req)) {
        res.getOutputStream().println("SUCCESS");
        return;
    }
    ResourceLocator settings = new ResourceLocator("com.stratelia.webactiv.util.attachment.Attachment", "");
    boolean actifyPublisherEnable = settings.getBoolean("ActifyPublisherEnable", false);
    try {
        req.setCharacterEncoding("UTF-8");
        String componentId = req.getParameter("ComponentId");
        SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                "componentId = " + componentId);
        String id = req.getParameter("PubId");
        SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "id = " + id);
        String userId = req.getParameter("UserId");
        SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "userId = " + userId);
        String context = req.getParameter("Context");
        boolean bIndexIt = StringUtil.getBooleanValue(req.getParameter("IndexIt"));

        List<FileItem> items = FileUploadUtil.parseRequest(req);
        for (FileItem item : items) {
            SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                    "item = " + item.getFieldName());
            SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                    "item = " + item.getName() + "; " + item.getString("UTF-8"));

            if (!item.isFormField()) {
                String fileName = item.getName();
                if (fileName != null) {
                    String physicalName = saveFileOnDisk(item, componentId, context);
                    String mimeType = AttachmentController.getMimeType(fileName);
                    long size = item.getSize();
                    SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                            "item size = " + size);
                    // create AttachmentDetail Object
                    AttachmentDetail attachment = new AttachmentDetail(
                            new AttachmentPK(null, "useless", componentId), physicalName, fileName, null,
                            mimeType, size, context, new Date(), new AttachmentPK(id, "useless", componentId));
                    attachment.setAuthor(userId);
                    try {
                        AttachmentController.createAttachment(attachment, bIndexIt);
                    } catch (Exception e) {
                        // storing data into DB failed, delete file just added on disk
                        deleteFileOnDisk(physicalName, componentId, context);
                        throw e;
                    }
                    // Specific case: 3d file to convert by Actify Publisher
                    if (actifyPublisherEnable) {
                        String extensions = settings.getString("Actify3dFiles");
                        StringTokenizer tokenizer = new StringTokenizer(extensions, ",");
                        // 3d native file ?
                        boolean fileForActify = false;
                        SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                                "nb tokenizer =" + tokenizer.countTokens());
                        String type = FileRepositoryManager.getFileExtension(fileName);
                        while (tokenizer.hasMoreTokens() && !fileForActify) {
                            String extension = tokenizer.nextToken();
                            fileForActify = type.equalsIgnoreCase(extension);
                        }
                        if (fileForActify) {
                            String dirDestName = "a_" + componentId + "_" + id;
                            String actifyWorkingPath = settings.getString("ActifyPathSource")
                                    + File.separatorChar + dirDestName;

                            String destPath = FileRepositoryManager.getTemporaryPath() + actifyWorkingPath;
                            if (!new File(destPath).exists()) {
                                FileRepositoryManager.createGlobalTempPath(actifyWorkingPath);
                            }
                            String normalizedFileName = FilenameUtils.normalize(fileName);
                            if (normalizedFileName == null) {
                                normalizedFileName = FilenameUtils.getName(fileName);
                            }
                            String destFile = FileRepositoryManager.getTemporaryPath() + actifyWorkingPath
                                    + File.separatorChar + normalizedFileName;
                            FileRepositoryManager
                                    .copyFile(AttachmentController.createPath(componentId, "Images")
                                            + File.separatorChar + physicalName, destFile);
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        SilverTrace.error("attachment", "DragAndDrop.doPost", "ERREUR", e);
        res.getOutputStream().println("ERROR");
        return;
    }
    res.getOutputStream().println("SUCCESS");
}