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

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

Introduction

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

Prototype

String getContentType();

Source Link

Document

Returns the content type passed by the browser or null if not defined.

Usage

From source file:com.mx.nibble.middleware.web.util.FileParse.java

public String execute(ActionInvocation invocation) throws Exception {

    Iterator iterator = parameters.entrySet().iterator();
    while (iterator.hasNext()) {
        Map.Entry mapEntry = (Map.Entry) iterator.next();
        System.out.println("The key is: " + mapEntry.getKey() + ",value is :" + mapEntry.getValue());
    }/*from   w  ww . java  2s  . co m*/

    ActionContext ac = invocation.getInvocationContext();

    HttpServletRequest request = (HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST);

    HttpServletResponse response = (HttpServletResponse) ac.get(ServletActionContext.HTTP_RESPONSE);
    /**
    * This pages gives a sample of java upload management. It needs the commons FileUpload library, which can be found on apache.org.
    *
    * Note:
    * - putting error=true as a parameter on the URL will generate an error. Allows test of upload error management in the applet. 
    * 
    * 
    * 
    * 
    * 
    * 
    */

    // Directory to store all the uploaded files
    String ourTempDirectory = "/opt/erp/import/obras/";

    byte[] cr = { 13 };
    byte[] lf = { 10 };
    String CR = new String(cr);
    String LF = new String(lf);
    String CRLF = CR + LF;
    System.out.println("Before a LF=chr(10)" + LF + "Before a CR=chr(13)" + CR + "Before a CRLF" + CRLF);

    //Initialization for chunk management.
    boolean bLastChunk = false;
    int numChunk = 0;

    //CAN BE OVERRIDEN BY THE postURL PARAMETER: if error=true is passed as a parameter on the URL
    boolean generateError = false;
    boolean generateWarning = false;
    boolean sendRequest = false;

    response.setContentType("text/plain");

    java.util.Enumeration<String> headers = request.getHeaderNames();
    System.out.println("[parseRequest.jsp]  ------------------------------ ");
    System.out.println("[parseRequest.jsp]  Headers of the received request:");
    while (headers.hasMoreElements()) {
        String header = headers.nextElement();
        System.out.println("[parseRequest.jsp]  " + header + ": " + request.getHeader(header));
    }
    System.out.println("[parseRequest.jsp]  ------------------------------ ");

    try {
        // Get URL Parameters.
        Enumeration paraNames = request.getParameterNames();
        System.out.println("[parseRequest.jsp]  ------------------------------ ");
        System.out.println("[parseRequest.jsp]  Parameters: ");
        String pname;
        String pvalue;
        while (paraNames.hasMoreElements()) {
            pname = (String) paraNames.nextElement();
            pvalue = request.getParameter(pname);
            System.out.println("[parseRequest.jsp] " + pname + " = " + pvalue);
            if (pname.equals("jufinal")) {
                bLastChunk = pvalue.equals("1");
            } else if (pname.equals("jupart")) {
                numChunk = Integer.parseInt(pvalue);
            }

            //For debug convenience, putting error=true as a URL parameter, will generate an error
            //in this response.
            if (pname.equals("error") && pvalue.equals("true")) {
                generateError = true;
            }

            //For debug convenience, putting warning=true as a URL parameter, will generate a warning
            //in this response.
            if (pname.equals("warning") && pvalue.equals("true")) {
                generateWarning = true;
            }

            //For debug convenience, putting readRequest=true as a URL parameter, will send back the request content
            //into the response of this page.
            if (pname.equals("sendRequest") && pvalue.equals("true")) {
                sendRequest = true;
            }

        }
        System.out.println("[parseRequest.jsp]  ------------------------------ ");

        int ourMaxMemorySize = 10000000;
        int ourMaxRequestSize = 2000000000;

        ///////////////////////////////////////////////////////////////////////////////////////////////////////
        //The code below is directly taken from the jakarta fileupload common classes
        //All informations, and download, available here : http://jakarta.apache.org/commons/fileupload/
        ///////////////////////////////////////////////////////////////////////////////////////////////////////

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

        // Set factory constraints
        factory.setSizeThreshold(ourMaxMemorySize);
        factory.setRepository(new File(ourTempDirectory));

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Set overall request size constraint
        upload.setSizeMax(ourMaxRequestSize);

        // Parse the request
        if (sendRequest) {
            //For debug only. Should be removed for production systems. 
            System.out.println(
                    "[parseRequest.jsp] ===========================================================================");
            System.out.println("[parseRequest.jsp] Sending the received request content: ");
            InputStream is = request.getInputStream();
            int c;
            while ((c = is.read()) >= 0) {
                out.write(c);
            } //while
            is.close();
            System.out.println(
                    "[parseRequest.jsp] ===========================================================================");
        } else if (!request.getContentType().startsWith("multipart/form-data")) {
            System.out.println("[parseRequest.jsp] No parsing of uploaded file: content type is "
                    + request.getContentType());
        } else {
            List /* FileItem */ items = upload.parseRequest(request);
            // Process the uploaded items
            Iterator iter = items.iterator();
            FileItem fileItem;
            File fout;
            System.out.println("[parseRequest.jsp]  Let's read the sent data   (" + items.size() + " items)");
            while (iter.hasNext()) {
                fileItem = (FileItem) iter.next();

                if (fileItem.isFormField()) {
                    System.out.println("[parseRequest.jsp] (form field) " + fileItem.getFieldName() + " = "
                            + fileItem.getString());

                    //If we receive the md5sum parameter, we've read finished to read the current file. It's not
                    //a very good (end of file) signal. Will be better in the future ... probably !
                    //Let's put a separator, to make output easier to read.
                    if (fileItem.getFieldName().equals("md5sum[]")) {
                        System.out.println("[parseRequest.jsp]  ------------------------------ ");
                    }
                } else {
                    //Ok, we've got a file. Let's process it.
                    //Again, for all informations of what is exactly a FileItem, please
                    //have a look to http://jakarta.apache.org/commons/fileupload/
                    //
                    System.out.println("[parseRequest.jsp] FieldName: " + fileItem.getFieldName());
                    System.out.println("[parseRequest.jsp] File Name: " + fileItem.getName());
                    System.out.println("[parseRequest.jsp] ContentType: " + fileItem.getContentType());
                    System.out.println("[parseRequest.jsp] Size (Bytes): " + fileItem.getSize());
                    //If we are in chunk mode, we add ".partN" at the end of the file, where N is the chunk number.
                    String uploadedFilename = fileItem.getName() + (numChunk > 0 ? ".part" + numChunk : "");
                    fout = new File(ourTempDirectory + (new File(uploadedFilename)).getName());
                    System.out.println("[parseRequest.jsp] File Out: " + fout.toString());
                    // write the file
                    fileItem.write(fout);

                    //////////////////////////////////////////////////////////////////////////////////////
                    //Chunk management: if it was the last chunk, let's recover the complete file
                    //by concatenating all chunk parts.
                    //
                    if (bLastChunk) {
                        System.out.println(
                                "[parseRequest.jsp]  Last chunk received: let's rebuild the complete file ("
                                        + fileItem.getName() + ")");
                        //First: construct the final filename.
                        FileInputStream fis;
                        FileOutputStream fos = new FileOutputStream(ourTempDirectory + fileItem.getName());
                        int nbBytes;
                        byte[] byteBuff = new byte[1024];
                        String filename;
                        for (int i = 1; i <= numChunk; i += 1) {
                            filename = fileItem.getName() + ".part" + i;
                            System.out.println("[parseRequest.jsp] " + "  Concatenating " + filename);
                            fis = new FileInputStream(ourTempDirectory + filename);
                            while ((nbBytes = fis.read(byteBuff)) >= 0) {
                                //System.out.println("[parseRequest.jsp] " + "     Nb bytes read: " + nbBytes);
                                fos.write(byteBuff, 0, nbBytes);
                            }
                            fis.close();
                        }
                        fos.close();
                    }

                    // End of chunk management
                    //////////////////////////////////////////////////////////////////////////////////////

                    fileItem.delete();
                }
            } //while
        }

        if (generateWarning) {
            System.out.println("WARNING: just a warning message.\\nOn two lines!");
        }

        System.out.println("[parseRequest.jsp] " + "Let's write a status, to finish the server response :");

        //Let's wait a little, to simulate the server time to manage the file.
        Thread.sleep(500);

        //Do you want to test a successful upload, or the way the applet reacts to an error ?
        if (generateError) {
            System.out.println(
                    "ERROR: this is a test error (forced in /wwwroot/pages/parseRequest.jsp).\\nHere is a second line!");
        } else {
            System.out.println("SUCCESS");
            PrintWriter out = ServletActionContext.getResponse().getWriter();
            out.write("SUCCESS");
            //System.out.println("                        <span class=\"cpg_user_message\">Il y eu une erreur lors de l'excution de la requte</span>");
        }

        System.out.println("[parseRequest.jsp] " + "End of server treatment ");

    } catch (Exception e) {
        System.out.println("");
        System.out.println("ERROR: Exception e = " + e.toString());
        System.out.println("");
    }

    return SUCCESS;

}

From source file:byps.http.HHttpServlet.java

protected void doHtmlUpload(HttpServletRequest request, HttpServletResponse response) throws IOException {
    if (log.isDebugEnabled())
        log.debug("doHtmlUpload(");

    try {// w  ww  . j  a va  2s  . c o  m
        // NDC.push(hsess.getId());

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart) {
            throw new IllegalStateException("File upload must be sent as multipart/form-data.");
        }

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory(HConstants.INCOMING_STREAM_BUFFER,
                getConfig().getTempDir());

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Set overall request size constraint
        long maxSize = getHtmlUploadMaxSize();
        if (log.isDebugEnabled())
            log.debug("set max upload file size=" + maxSize);
        upload.setSizeMax(maxSize);

        // Parse the request
        @SuppressWarnings("unchecked")
        List<FileItem> items = upload.parseRequest(request);
        if (log.isDebugEnabled())
            log.debug("received #items=" + items.size());

        ArrayList<HFileUploadItem> uploadItems = new ArrayList<HFileUploadItem>();
        for (FileItem item : items) {

            String fieldName = item.getFieldName();
            if (log.isDebugEnabled())
                log.debug("fieldName=" + fieldName);
            String fileName = item.getName();
            if (log.isDebugEnabled())
                log.debug("fileName=" + fileName);
            boolean formField = item.isFormField();
            if (log.isDebugEnabled())
                log.debug("formField=" + formField);
            if (!formField && fileName.length() == 0)
                continue;
            long streamId = formField ? 0L
                    : (System.currentTimeMillis()
                            ^ ((((long) fileName.hashCode()) << 16L) | (long) System.identityHashCode(this))); // used as pseudo random number

            HFileUploadItem uploadItem = new HFileUploadItem(formField, fieldName, fileName,
                    item.getContentType(), item.getSize(), Long.toString(streamId));
            uploadItems.add(uploadItem);
            if (log.isDebugEnabled())
                log.debug("uploadItem=" + uploadItem);

            if (item.isFormField())
                continue;

            final BTargetId targetId = new BTargetId(getConfig().getMyServerId(), 0, streamId);
            getActiveMessages().addIncomingUploadStream(
                    new HFileUploadItemIncomingStream(item, targetId, getConfig().getTempDir()));

        }

        makeHtmlUploadResult(request, response, uploadItems);

    } catch (Throwable e) {
        if (log.isInfoEnabled())
            log.info("Failed to process message.", e);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().print(e.toString());
        response.getWriter().close();
    } finally {
        // NDC.pop();
    }

    if (log.isDebugEnabled())
        log.debug(")doHtmlUpload");
}

From source file:com.Voxce.Controllers.TrialsController.java

public ModelAndView SubmitUserCV(HttpServletRequest request, HttpServletResponse response) throws Exception {
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new IllegalArgumentException(
                "Request is not multipart, please 'multipart/form-data' enctype for your form.");
    }/*from w  w w. j  a v a  2  s  .c o m*/

    List<FileItem> CVitems;

    ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());
    PrintWriter writer = response.getWriter();
    response.setContentType("text/plain");
    try {
        CVitems = uploadHandler.parseRequest(request);
        for (FileItem item2 : CVitems) {
            if (!item2.isFormField()) {
                if (item2.getSize() > 9999000) {
                    writer.write("{\"name\":\"" + "Sorry File Size is larger then 9 MB" + "\",\"type\":\""
                            + item2.getContentType() + "\",\"size\":\"" + item2.getSize() + "\"}");
                    break; // assume we only get one file at a time
                } else {
                    CVitem = item2;
                    //   
                    System.out.println("Name =" + item2.getName() + "  Size=" + item2.getSize() + " type ="
                            + item2.getContentType());
                    writer.write("{\"name\":\"" + item2.getName() + "\",\"type\":\"" + item2.getContentType()
                            + "\",\"size\":\"" + item2.getSize() + "\"}");
                    break; // assume we only get one file at a time
                }
            }
        }
    } catch (FileUploadException e) {
        throw new RuntimeException(e);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        writer.close();
    }
    return new ModelAndView("usercv");
}

From source file:com.Voxce.Controllers.TrialsController.java

public ModelAndView UploadContract(HttpServletRequest request, HttpServletResponse response) throws Exception {

    if (!ServletFileUpload.isMultipartContent(request)) {

        throw new IllegalArgumentException(
                "Request is not multipart, please 'multipart/form-data' enctype for your form.");
    }//from  w  w w . j a  va  2s .c om

    ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());
    PrintWriter writer = response.getWriter();
    response.setContentType("text/plain");

    List<FileItem> Contractitems;

    try {
        Contractitems = uploadHandler.parseRequest(request);
        for (FileItem item2 : Contractitems) {
            if (!item2.isFormField()) {
                if (item2.getSize() > 9999000) {
                    writer.write("{\"name\":\"" + "Sorry File Size is larger then 9 MB" + "\",\"type\":\""
                            + item2.getContentType() + "\",\"size\":\"" + item2.getSize() + "\"}");
                    break; // assume we only get one file at a time
                } else {
                    Contractitem = item2;
                    System.out.println("Name =" + item2.getName() + "  Size=" + item2.getSize() + " type ="
                            + item2.getContentType());
                    writer.write("{\"name\":\"" + item2.getName() + "\",\"type\":\"" + item2.getContentType()
                            + "\",\"size\":\"" + item2.getSize() + "\"}");
                    break; // assume we only get one file at a time
                }
            }
        }
    } catch (FileUploadException e) {
        throw new RuntimeException(e);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        writer.close();
    }

    return new ModelAndView("contracts");
}

From source file:com.Voxce.Controllers.TrialsController.java

@SuppressWarnings("unchecked")
public ModelAndView UploadTrainingUser(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    if (!ServletFileUpload.isMultipartContent(request)) {

        throw new IllegalArgumentException(
                "Request is not multipart, please 'multipart/form-data' enctype for your form.");
    }/*from w  w  w  .j a va 2s  .c om*/

    List<FileItem> traininguseritems;

    ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());
    PrintWriter writer = response.getWriter();
    response.setContentType("text/plain");
    try {
        traininguseritems = uploadHandler.parseRequest(request);
        for (FileItem item2 : traininguseritems) {
            if (!item2.isFormField()) {
                if (item2.getSize() > 9999000) {
                    writer.write("{\"name\":\"" + "Sorry File Size is larger then 9 MB" + "\",\"type\":\""
                            + item2.getContentType() + "\",\"size\":\"" + item2.getSize() + "\"}");
                    break; // assume we only get one file at a time
                } else {
                    traininguseritem = item2;
                    writer.write("{\"name\":\"" + item2.getName() + "\",\"type\":\"" + item2.getContentType()
                            + "\",\"size\":\"" + item2.getSize() + "\"}");
                    break; // assume we only get one file at a time
                }
            }
        }
    } catch (FileUploadException e) {
        throw new RuntimeException(e);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        writer.close();
    }

    return new ModelAndView("training_user");
}

From source file:com.Voxce.Controllers.TrialsController.java

public ModelAndView UploadSubmissions(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    //=================================================================================================================================================================//

    if (!ServletFileUpload.isMultipartContent(request)) {

        throw new IllegalArgumentException(
                "Request is not multipart, please 'multipart/form-data' enctype for your form.");
    }/*from   w w w  . j a v a2s.  c om*/

    List<FileItem> submissionitems;

    ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());
    PrintWriter writer = response.getWriter();
    response.setContentType("text/plain");
    try {
        submissionitems = uploadHandler.parseRequest(request);
        for (FileItem item2 : submissionitems) {
            if (!item2.isFormField()) {
                if (item2.getSize() > 9999000) {
                    writer.write("{\"name\":\"" + "Sorry File Size is larger then 9 MB" + "\",\"type\":\""
                            + item2.getContentType() + "\",\"size\":\"" + item2.getSize() + "\"}");
                    break; // assume we only get one file at a time
                } else {
                    submissionitem = item2;
                    //   
                    System.out.println("Name =" + item2.getName() + "  Size=" + item2.getSize() + " type ="
                            + item2.getContentType());
                    writer.write("{\"name\":\"" + item2.getName() + "\",\"type\":\"" + item2.getContentType()
                            + "\",\"size\":\"" + item2.getSize() + "\"}");
                    break; // assume we only get one file at a time
                }
            }
        }
    } catch (FileUploadException e) {
        throw new RuntimeException(e);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        writer.close();
    }
    return new ModelAndView("submissions");
}

From source file:com.Voxce.Controllers.TrialsController.java

public ModelAndView UploadFinancialDisc(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    if (!ServletFileUpload.isMultipartContent(request)) {

        throw new IllegalArgumentException(
                "Request is not multipart, please 'multipart/form-data' enctype for your form.");
    }/*w w w .  j a v a 2  s  .  co m*/

    ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());
    PrintWriter writer = response.getWriter();
    response.setContentType("text/plain");

    List<FileItem> Financialdiscitems;

    try {
        Financialdiscitems = uploadHandler.parseRequest(request);
        for (FileItem item2 : Financialdiscitems) {
            if (!item2.isFormField()) {
                if (item2.getSize() > 9999000) {
                    writer.write("{\"name\":\"" + "Sorry File Size is larger then 9 MB" + "\",\"type\":\""
                            + item2.getContentType() + "\",\"size\":\"" + item2.getSize() + "\"}");
                    break; // assume we only get one file at a time
                } else {
                    Financialdiscitem = item2;
                    //   
                    System.out.println("Name =" + item2.getName() + "  Size=" + item2.getSize() + " type ="
                            + item2.getContentType());
                    writer.write("{\"name\":\"" + item2.getName() + "\",\"type\":\"" + item2.getContentType()
                            + "\",\"size\":\"" + item2.getSize() + "\"}");
                    break; // assume we only get one file at a time
                }
            }
        }
    } catch (FileUploadException e) {
        throw new RuntimeException(e);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        writer.close();
    }

    return new ModelAndView("financial_disc");
}

From source file:com.Voxce.Controllers.TrialsController.java

@SuppressWarnings("unchecked")
public ModelAndView UploadMedicalLicense(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    if (!ServletFileUpload.isMultipartContent(request)) {

        throw new IllegalArgumentException(
                "Request is not multipart, please 'multipart/form-data' enctype for your form.");
    }//from   w ww .j a va  2s  . com

    List<FileItem> medicallicenseitems;

    ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());
    PrintWriter writer = response.getWriter();
    response.setContentType("text/plain");
    try {
        medicallicenseitems = uploadHandler.parseRequest(request);
        for (FileItem item2 : medicallicenseitems) {
            if (!item2.isFormField()) {
                if (item2.getSize() > 9999000) {
                    writer.write("{\"name\":\"" + "Sorry File Size is larger then 9 MB" + "\",\"type\":\""
                            + item2.getContentType() + "\",\"size\":\"" + item2.getSize() + "\"}");
                    break; // assume we only get one file at a time
                } else {
                    medicallicenseitem = item2;
                    //   
                    System.out.println("Name =" + item2.getName() + "  Size=" + item2.getSize() + " type ="
                            + item2.getContentType());
                    writer.write("{\"name\":\"" + item2.getName() + "\",\"type\":\"" + item2.getContentType()
                            + "\",\"size\":\"" + item2.getSize() + "\"}");
                    break; // assume we only get one file at a time
                }
            }
        }
    } catch (FileUploadException e) {
        throw new RuntimeException(e);
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        writer.close();
    }
    return new ModelAndView("medical_license");
}

From source file:de.betterform.agent.web.servlet.HttpRequestHandler.java

protected void processUploadParameters(Map uploads, HttpServletRequest request) throws XFormsException {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("updating " + uploads.keySet().size() + " uploads(s)");
    }// w  w  w  .jav a 2 s.c o  m

    try {
        // update repeat indices
        Iterator iterator = uploads.keySet().iterator();
        String id;
        FileItem item;
        byte[] data;

        while (iterator.hasNext()) {
            id = (String) iterator.next();
            item = (FileItem) uploads.get(id);

            if (item.getSize() > 0) {
                LOGGER.debug("i'm here");
                if (this.xformsProcessor.isFileUpload(id, "anyURI")) {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("found upload type 'anyURI'");
                    }
                    String localPath = new StringBuffer().append(System.currentTimeMillis()).append('/')
                            .append(item.getName()).toString();

                    File localFile = new File(this.uploadRoot, localPath);
                    localFile.getParentFile().mkdirs();
                    item.write(localFile);

                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("saving data to path: " + localFile);
                    }

                    // todo: externalize file handling and uri generation

                    File uploadDir = new File(request.getContextPath(),
                            Config.getInstance().getProperty(WebFactory.UPLOADDIR_PROPERTY));
                    String urlEncodedPath = URLEncoder
                            .encode(new File(uploadDir.getPath(), localPath).getPath(), "UTF-8");
                    URI uploadTargetDir = new URI(urlEncodedPath);

                    data = uploadTargetDir.toString().getBytes();
                } else {
                    data = item.get();
                }

                this.xformsProcessor.setUploadValue(id, item.getContentType(), item.getName(), data);

                // After the value has been set and the RRR took place, create new UploadInfo with status set to 'done'
                request.getSession().setAttribute(WebProcessor.ADAPTER_PREFIX + sessionKey + "-uploadInfo",
                        new UploadInfo(1, 0, 0, 0, "done"));
            } else {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("ignoring empty upload " + id);
                }
                // todo: removal ?
            }

            item.delete();
        }
    } catch (Exception e) {
        throw new XFormsException(e);
    }
}

From source file:fr.paris.lutece.plugins.document.service.DocumentService.java

/**
 * Update the specify attribute with the mRequest parameters
 *
 * @param attribute The {@link DocumentAttribute} to update
 * @param document The {@link Document}/*from  w w w .j  ava2s.  co m*/
 * @param mRequest The multipart http request
 * @param locale The locale
 * @return an admin message if error or null else
 */
private String setAttribute(DocumentAttribute attribute, Document document,
        MultipartHttpServletRequest mRequest, Locale locale) {
    String strParameterStringValue = mRequest.getParameter(attribute.getCode());
    FileItem fileParameterBinaryValue = mRequest.getFile(attribute.getCode());
    String strIsUpdatable = mRequest.getParameter(PARAMETER_ATTRIBUTE_UPDATE + attribute.getCode());
    String strToResize = mRequest.getParameter(attribute.getCode() + PARAMETER_CROPPABLE);
    boolean bIsUpdatable = ((strIsUpdatable == null) || strIsUpdatable.equals("")) ? false : true;
    boolean bToResize = ((strToResize == null) || strToResize.equals("")) ? false : true;

    if (strParameterStringValue != null) // If the field is a string
    {
        // Check for mandatory value
        if (attribute.isRequired() && strParameterStringValue.trim().equals("")) {
            return AdminMessageService.getMessageUrl(mRequest, Messages.MANDATORY_FIELDS,
                    AdminMessage.TYPE_STOP);
        }

        // Check for specific attribute validation
        AttributeManager manager = AttributeService.getInstance().getManager(attribute.getCodeAttributeType());
        String strValidationErrorMessage = manager.validateValue(attribute.getId(), strParameterStringValue,
                locale);

        if (strValidationErrorMessage != null) {
            String[] listArguments = { attribute.getName(), strValidationErrorMessage };

            return AdminMessageService.getMessageUrl(mRequest, MESSAGE_ATTRIBUTE_VALIDATION_ERROR,
                    listArguments, AdminMessage.TYPE_STOP);
        }

        attribute.setTextValue(strParameterStringValue);
    } else if (fileParameterBinaryValue != null) // If the field is a file
    {
        attribute.setBinary(true);

        String strContentType = fileParameterBinaryValue.getContentType();
        byte[] bytes = fileParameterBinaryValue.get();
        String strFileName = fileParameterBinaryValue.getName();
        String strExtension = FilenameUtils.getExtension(strFileName);

        AttributeManager manager = AttributeService.getInstance().getManager(attribute.getCodeAttributeType());

        if (!bIsUpdatable) {
            // there is no new value then take the old file value
            DocumentAttribute oldAttribute = document.getAttribute(attribute.getCode());

            if ((oldAttribute != null) && (oldAttribute.getBinaryValue() != null)
                    && (oldAttribute.getBinaryValue().length > 0)) {
                bytes = oldAttribute.getBinaryValue();
                strContentType = oldAttribute.getValueContentType();
                strFileName = oldAttribute.getTextValue();
                strExtension = FilenameUtils.getExtension(strFileName);
            }
        }

        List<AttributeTypeParameter> parameters = manager.getExtraParametersValues(locale, attribute.getId());

        String extensionList = StringUtils.EMPTY;

        if (CollectionUtils.isNotEmpty(parameters)
                && CollectionUtils.isNotEmpty(parameters.get(0).getValueList())) {
            extensionList = parameters.get(0).getValueList().get(0);
        }

        // Check for mandatory value
        if (attribute.isRequired() && ((bytes == null) || (bytes.length == 0))) {
            return AdminMessageService.getMessageUrl(mRequest, Messages.MANDATORY_FIELDS,
                    AdminMessage.TYPE_STOP);
        } else if (StringUtils.isNotBlank(extensionList) && !extensionList.contains(strExtension)) {
            Object[] params = new Object[2];
            params[0] = attribute.getName();
            params[1] = extensionList;

            return AdminMessageService.getMessageUrl(mRequest, MESSAGE_EXTENSION_ERROR, params,
                    AdminMessage.TYPE_STOP);
        }

        // Check for specific attribute validation
        String strValidationErrorMessage = manager.validateValue(attribute.getId(), strFileName, locale);

        if (strValidationErrorMessage != null) {
            String[] listArguments = { attribute.getName(), strValidationErrorMessage };

            return AdminMessageService.getMessageUrl(mRequest, MESSAGE_ATTRIBUTE_VALIDATION_ERROR,
                    listArguments, AdminMessage.TYPE_STOP);
        }

        if (bToResize && !ArrayUtils.isEmpty(bytes)) {
            // Resize image
            String strWidth = mRequest.getParameter(attribute.getCode() + PARAMETER_WIDTH);

            if (StringUtils.isBlank(strWidth) || !StringUtils.isNumeric(strWidth)) {
                String[] listArguments = { attribute.getName(),
                        I18nService.getLocalizedString(MESSAGE_ATTRIBUTE_WIDTH_ERROR, mRequest.getLocale()) };

                return AdminMessageService.getMessageUrl(mRequest, MESSAGE_ATTRIBUTE_VALIDATION_ERROR,
                        listArguments, AdminMessage.TYPE_STOP);
            }

            try {
                bytes = ImageUtils.resizeImage(bytes, Integer.valueOf(strWidth));
            } catch (IOException e) {
                return AdminMessageService.getMessageUrl(mRequest, MESSAGE_ATTRIBUTE_RESIZE_ERROR,
                        AdminMessage.TYPE_STOP);
            }
        }

        attribute.setBinaryValue(bytes);
        attribute.setValueContentType(strContentType);
        attribute.setTextValue(strFileName);
    }

    return null;
}