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

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

Introduction

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

Prototype

byte[] get();

Source Link

Document

Returns the contents of the file item as an array of bytes.

Usage

From source file:com.alkacon.opencms.v8.formgenerator.CmsFormHandler.java

/**
 * Sends the mail with the form data to the specified recipients.<p>
 * //from ww w  . jav  a  2 s. c o  m
 * If configured, sends also a confirmation mail to the form submitter.<p>
 * 
 * @return true if the mail has been successfully sent, otherwise false
 */
protected boolean sendMail() {

    try {
        // create the new mail message depending on the configured email type
        if (getFormConfiguration().getMailType().equals(CmsForm.MAILTYPE_HTML)) {
            // create a HTML email
            CmsHtmlMail theMail = new CmsHtmlMail();
            theMail.setCharset(getCmsObject().getRequestContext().getEncoding());
            if (CmsStringUtil.isNotEmpty(getFormConfiguration().getMailFrom())) {
                if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(getFormConfiguration().getMailFromName())) {
                    theMail.setFrom(m_macroResolver.resolveMacros(getFormConfiguration().getMailFrom()),
                            m_macroResolver.resolveMacros(getFormConfiguration().getMailFromName()));
                } else {
                    theMail.setFrom(m_macroResolver.resolveMacros(getFormConfiguration().getMailFrom()));
                }
            }
            theMail.setTo(createInternetAddresses(getFormConfiguration().getMailTo()));
            List<InternetAddress> ccRec = createInternetAddresses(
                    m_macroResolver.resolveMacros(getFormConfiguration().getMailCC()));
            if (ccRec.size() > 0) {
                theMail.setCc(ccRec);
            }
            List<InternetAddress> bccRec = createInternetAddresses(
                    m_macroResolver.resolveMacros(getFormConfiguration().getMailBCC()));
            if (bccRec.size() > 0) {
                theMail.setBcc(bccRec);
            }
            theMail.setSubject(m_macroResolver.resolveMacros(
                    getFormConfiguration().getMailSubjectPrefix() + getFormConfiguration().getMailSubject()));
            theMail.setHtmlMsg(createMailTextFromFields(true, false));

            // attach file uploads
            Map<String, FileItem> fileUploads = getFileUploads();
            if (fileUploads != null) {
                Iterator<FileItem> i = fileUploads.values().iterator();
                while (i.hasNext()) {
                    FileItem attachment = i.next();
                    if (attachment != null) {
                        String filename = attachment.getName()
                                .substring(attachment.getName().lastIndexOf(File.separator) + 1);
                        theMail.attach(new CmsByteArrayDataSource(filename, attachment.get(), OpenCms
                                .getResourceManager().getMimeType(filename, null, "application/octet-stream")),
                                filename, filename);
                    }
                }
            }
            // send the mail
            theMail.send();
        } else {
            // create a plain text email
            CmsSimpleMail theMail = new CmsSimpleMail();
            theMail.setCharset(getCmsObject().getRequestContext().getEncoding());
            if (CmsStringUtil.isNotEmpty(getFormConfiguration().getMailFrom())) {
                if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(getFormConfiguration().getMailFromName())) {
                    theMail.setFrom(m_macroResolver.resolveMacros(getFormConfiguration().getMailFrom()),
                            m_macroResolver.resolveMacros(getFormConfiguration().getMailFromName()));
                } else {
                    theMail.setFrom(m_macroResolver.resolveMacros(getFormConfiguration().getMailFrom()));
                }
            }
            theMail.setTo(createInternetAddresses(getFormConfiguration().getMailTo()));
            List<InternetAddress> ccRec = createInternetAddresses(
                    m_macroResolver.resolveMacros(getFormConfiguration().getMailCC()));
            if (ccRec.size() > 0) {
                theMail.setCc(ccRec);
            }
            List<InternetAddress> bccRec = createInternetAddresses(
                    m_macroResolver.resolveMacros(getFormConfiguration().getMailBCC()));
            if (bccRec.size() > 0) {
                theMail.setBcc(bccRec);
            }
            theMail.setSubject(m_macroResolver.resolveMacros(
                    getFormConfiguration().getMailSubjectPrefix() + getFormConfiguration().getMailSubject()));
            theMail.setMsg(createMailTextFromFields(false, false));
            // send the mail
            theMail.send();
        }
    } catch (Exception e) {
        // an error occured during mail creation
        if (LOG.isErrorEnabled()) {
            LOG.error(e.getLocalizedMessage(), e);
        }
        getErrors().put("sendmail", e.getMessage());
        return false;
    }
    return true;
}

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 ww .  j  ava  2  s  . 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;
}

From source file:it.geosolutions.httpproxy.HTTPProxy.java

/**
 * Sets up the given {@link PostMethod} to send the same multipart POST data as was sent in the given {@link HttpServletRequest}
 * //from w w  w . ja  v  a 2 s.com
 * @param postMethodProxyRequest The {@link PostMethod} that we are configuring to send a multipart POST request
 * @param httpServletRequest The {@link HttpServletRequest} that contains the mutlipart POST data to be sent via the {@link PostMethod}
 */
private void handleMultipart(EntityEnclosingMethod methodProxyRequest, HttpServletRequest httpServletRequest)
        throws ServletException {

    // ////////////////////////////////////////////
    // Create a factory for disk-based file items
    // ////////////////////////////////////////////

    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

    // /////////////////////////////
    // Set factory constraints
    // /////////////////////////////

    diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize());
    diskFileItemFactory.setRepository(Utils.DEFAULT_FILE_UPLOAD_TEMP_DIRECTORY);

    // //////////////////////////////////
    // Create a new file upload handler
    // //////////////////////////////////

    ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);

    // //////////////////////////
    // Parse the request
    // //////////////////////////

    try {

        // /////////////////////////////////////
        // Get the multipart items as a list
        // /////////////////////////////////////

        List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest);

        // /////////////////////////////////////////
        // Create a list to hold all of the parts
        // /////////////////////////////////////////

        List<Part> listParts = new ArrayList<Part>();

        // /////////////////////////////////////////
        // Iterate the multipart items list
        // /////////////////////////////////////////

        for (FileItem fileItemCurrent : listFileItems) {

            // //////////////////////////////////////
            // If the current item is a form field,
            // then create a string part
            // //////////////////////////////////////

            if (fileItemCurrent.isFormField()) {
                StringPart stringPart = new StringPart(
                        // The field name
                        fileItemCurrent.getFieldName(),
                        // The field value
                        fileItemCurrent.getString());

                // ////////////////////////////
                // Add the part to the list
                // ////////////////////////////

                listParts.add(stringPart);

            } else {

                // /////////////////////////////////////////////////////
                // The item is a file upload, so we create a FilePart
                // /////////////////////////////////////////////////////

                FilePart filePart = new FilePart(

                        // /////////////////////
                        // The field name
                        // /////////////////////

                        fileItemCurrent.getFieldName(),

                        new ByteArrayPartSource(
                                // The uploaded file name
                                fileItemCurrent.getName(),
                                // The uploaded file contents
                                fileItemCurrent.get()));

                // /////////////////////////////
                // Add the part to the list
                // /////////////////////////////

                listParts.add(filePart);
            }
        }

        MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(
                listParts.toArray(new Part[] {}), methodProxyRequest.getParams());

        methodProxyRequest.setRequestEntity(multipartRequestEntity);

        // ////////////////////////////////////////////////////////////////////////
        // The current content-type header (received from the client) IS of
        // type "multipart/form-data", but the content-type header also
        // contains the chunk boundary string of the chunks. Currently, this
        // header is using the boundary of the client request, since we
        // blindly copied all headers from the client request to the proxy
        // request. However, we are creating a new request with a new chunk
        // boundary string, so it is necessary that we re-set the
        // content-type string to reflect the new chunk boundary string
        // ////////////////////////////////////////////////////////////////////////

        methodProxyRequest.setRequestHeader(Utils.CONTENT_TYPE_HEADER_NAME,
                multipartRequestEntity.getContentType());

    } catch (FileUploadException fileUploadException) {
        throw new ServletException(fileUploadException);
    }
}

From source file:fr.paris.lutece.plugins.workflow.web.WorkflowJspBean.java

public String doImportWorkflow(HttpServletRequest request)
        throws JsonParseException, IOException, ClassNotFoundException {
    String contentType = request.getContentType();
    if (contentType.indexOf("multipart/form-data") >= 0) {
        MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
        FileItem item = mRequest.getFile("import_file");

        if ((item != null) && (item.getName() != null) && StringUtils.isNotBlank(item.getName())) {
            byte[] bytes = item.get();
            String json = new String(bytes);
            boolean res = parseJSON(json);
            if (res) {
                return AdminMessageService.getMessageUrl(request, MESSAGE_DUPLICATED_WORKFLOW,
                        AdminMessage.TYPE_ERROR);

            }/*  w w w  . j a  va 2s. com*/
        }
    }
    return getJspManageWorkflow(request);
}

From source file:com.alkacon.opencms.formgenerator.CmsForm.java

/**
 * Initializes the field objects of the form.<p>
 * /*from  w  w  w .  ja  v a2  s .  c  o m*/
 * @param xPath the xPath of the input field to initialize
 * @param content the XML configuration content
 * @param jsp the initialized CmsJspActionElement to access the OpenCms API
 * @param locale the currently active Locale
 * @param messages the localized messages
 * @param fieldTexts the optional field texts
 * @param subFieldPaths the optional sub field xPaths
 * @param fileUploads the uploaded files
 * @param subFieldNameSuffix the suffix for the sub field name used to create the HTML code and request parameter names
 * @param initial if true, field values are filled with values specified in the XML configuration, otherwise values are read from the request
 * @param subField indicates if a sub field should be created
 * 
 * @return an initialized input field
 * 
 * @throws CmsConfigurationException if parsing the configuration fails 
 */
private I_CmsField createInputField(String xPath, CmsXmlContent content, CmsJspActionElement jsp, Locale locale,
        CmsMessages messages, Map<String, CmsFieldText> fieldTexts, Map<String, List<String>> subFieldPaths,
        Map<String, FileItem> fileUploads, String subFieldNameSuffix, boolean initial, boolean subField)
        throws CmsConfigurationException {

    CmsObject cms = jsp.getCmsObject();

    // create the xPath prefix
    String inputFieldPath = xPath + "/";

    // get the field from the factory for the specified type
    // important: we don't use getContentStringValue, since the path comes directly from the input field
    String stringValue = content.getStringValue(cms, inputFieldPath + NODE_FIELDTYPE, locale);
    I_CmsField field = getField(stringValue);

    // get the field labels
    stringValue = content.getStringValue(cms, inputFieldPath + NODE_FIELDLABEL, locale);

    String locLabel = getConfigurationValue(stringValue, "");
    String dbLabel = locLabel;
    boolean useDbLabel = false;
    int pos = locLabel.indexOf('|');
    if (pos > -1) {
        locLabel = locLabel.substring(0, pos);
        if ((pos + 1) < dbLabel.length()) {
            dbLabel = dbLabel.substring(pos + 1);
            useDbLabel = true;
        }
    }
    field.setLabel(locLabel);
    field.setDbLabel(dbLabel);

    // create the field name
    String fieldName = xPath;
    // cut off the XML content index ("[number]") 
    int indexStart = fieldName.lastIndexOf('[') + 1;
    String index = fieldName.substring(indexStart, fieldName.length() - 1);
    if (useDbLabel) {
        // set field name to db label
        fieldName = dbLabel;
        field.setName(fieldName);
    } else {
        // set the field name to generic value "InputField-number"
        // replace the index ("[number]") of the xmlcontent field by "-number":
        fieldName = new StringBuffer(fieldName.substring(0, indexStart - 1)).append('-').append(index)
                .toString();
        // cut off initial path all but the last path segments
        // (make sure there is a slash in the string first).
        fieldName = "/" + fieldName;
        int slashIndex = fieldName.lastIndexOf("/");
        fieldName = fieldName.substring(slashIndex + 1);
        field.setName(fieldName + subFieldNameSuffix);
    }

    // get the optional text that is shown below the field
    CmsFieldText fieldText = fieldTexts.get(dbLabel);
    if (fieldText != null) {
        field.setText(fieldText);
    }

    // get the optional subfields
    if (!subField) {
        List<String> subFieldPathList = subFieldPaths.get(dbLabel);
        if (subFieldPathList != null) {
            // there are sub fields defined for this input field
            for (Iterator<String> i = subFieldPathList.iterator(); i.hasNext();) {
                String subPath = i.next() + "/";
                String fieldValue = content.getStringValue(cms, subPath + NODE_VALUE, locale);
                if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(fieldValue)) {
                    // a field value is specified, add the sub fields for the value
                    String suffix = new StringBuffer("-").append(index).append("-")
                            .append(fieldValue.hashCode()).toString();
                    List<I_CmsXmlContentValue> fieldValues = content.getValues(subPath + NODE_INPUTFIELD,
                            locale);
                    for (Iterator<I_CmsXmlContentValue> k = fieldValues.iterator(); k.hasNext();) {
                        field.addSubField(fieldValue, createInputField(k.next().getPath(), content, jsp, locale,
                                messages, fieldTexts, subFieldPaths, fileUploads, suffix, initial, true));
                    }
                }
            }
        }
    } else {
        // mark this field as sub field
        field.setSubField(subField);
    }

    // get the field parameters
    stringValue = content.getStringValue(cms, inputFieldPath + NODE_FIELDPARAMS, locale);
    field.setParameters(stringValue);

    // validation error message
    stringValue = content.getStringValue(cms, inputFieldPath + NODE_FIELDERRORMESSAGE, locale);
    field.setErrorMessage(stringValue);

    // fill object members in case this is no hidden field
    if (!CmsHiddenField.class.isAssignableFrom(field.getClass())) {
        // get the field validation regular expression
        stringValue = content.getStringValue(cms, inputFieldPath + NODE_FIELDVALIDATION, locale);
        if (CmsEmailField.class.isAssignableFrom(field.getClass()) && CmsStringUtil.isEmpty(stringValue)) {
            // set default email validation expression for confirmation email address input field
            field.setValidationExpression(CmsEmailField.VALIDATION_REGEX);
        } else {
            field.setValidationExpression(getConfigurationValue(stringValue, ""));
        }
        if (CmsFileUploadField.class.isAssignableFrom(field.getClass())) {
            if (fileUploads != null) {
                FileItem attachment = fileUploads.get(field.getName());
                if (attachment != null) {
                    ((CmsFileUploadField) field).setFileSize(attachment.get().length);
                }
            }
        }

        // get the field mandatory flag
        stringValue = content.getStringValue(cms, inputFieldPath + NODE_FIELDMANDATORY, locale);
        boolean isMandatory = Boolean.valueOf(stringValue).booleanValue();
        field.setMandatory(isMandatory);
        if (isMandatory) {
            // set flag that determines if mandatory fields are present
            setHasMandatoryFields(true);
        }

        // special case by table fields 
        if (CmsTableField.class.isAssignableFrom(field.getClass())) {
            CmsTableField tableField = (CmsTableField) field;
            String fieldValue = content.getStringValue(

                    cms, inputFieldPath + NODE_FIELDDEFAULTVALUE, locale);
            tableField.parseDefault(fieldValue, m_parameterMap);
        }

        if (field.needsItems()) {
            // create items for checkboxes, radio buttons and selectboxes
            String fieldValue = content.getStringValue(

                    cms, inputFieldPath + NODE_FIELDDEFAULTVALUE, locale);
            if (CmsStringUtil.isNotEmpty(fieldValue)) {
                // get items from String 
                boolean showInRow = false;
                if (fieldValue.startsWith(MACRO_SHOW_ITEMS_IN_ROW)) {
                    showInRow = true;
                    fieldValue = fieldValue.substring(MACRO_SHOW_ITEMS_IN_ROW.length());
                }
                StringTokenizer T = new StringTokenizer(fieldValue, "|");
                List<CmsFieldItem> items = new ArrayList<CmsFieldItem>(T.countTokens());
                while (T.hasMoreTokens()) {
                    String part = T.nextToken();
                    // check pre selection of current item
                    boolean isPreselected = part.indexOf('*') != -1;
                    String value = "";
                    String label = "";
                    String selected = "";
                    int delimPos = part.indexOf(':');
                    if (delimPos != -1) {
                        // a special label text is given
                        value = part.substring(0, delimPos);
                        label = part.substring(delimPos + 1);
                    } else {
                        // no special label text present, use complete String
                        value = part;
                        label = value;
                    }

                    if (isPreselected) {
                        // remove preselected flag marker from Strings
                        value = CmsStringUtil.substitute(value, "*", "");
                        label = CmsStringUtil.substitute(label, "*", "");
                    }

                    if (initial) {
                        // only fill in values from configuration file if called initially
                        if (isPreselected) {
                            selected = Boolean.toString(true);
                        }
                    } else {
                        // get selected flag from request for current item
                        selected = readSelectedFromRequest(field, value);
                    }

                    // add new item object
                    items.add(new CmsFieldItem(value, label, Boolean.valueOf(selected).booleanValue(),
                            showInRow));

                }
                field.setItems(items);
            } else {
                // no items specified for checkbox, radio button or selectbox
                throw new CmsConfigurationException(Messages.get().container(
                        Messages.ERR_INIT_INPUT_FIELD_MISSING_ITEM_2, field.getName(), field.getType()));
            }
        }
    }
    // get the field value
    if (initial && CmsStringUtil.isEmpty(getParameter(field.getName()))
            && !CmsTableField.class.isAssignableFrom(field.getClass())) {
        // only fill in values from configuration file if called initially
        if (!field.needsItems()) {
            if (CmsDisplayField.class.isAssignableFrom(field.getClass())
                    || CmsHiddenDisplayField.class.isAssignableFrom(field.getClass())) {
                String fieldValue = getDynamicFieldValue((CmsDynamicField) field);
                field.setValue(fieldValue);
            } else {
                String fieldValue = content.getStringValue(cms, inputFieldPath + NODE_FIELDDEFAULTVALUE,
                        locale);
                if (CmsStringUtil.isNotEmpty(fieldValue)) {
                    CmsMacroResolver resolver = CmsMacroResolver.newInstance().setCmsObject(cms)
                            .setJspPageContext(jsp.getJspContext());
                    fieldValue = resolver.resolveMacros(fieldValue);
                    field.setValue(fieldValue.trim());
                }
            }
        } else {
            // for field that needs items, 
            // the default value is used to set the items and not really a value
            field.setValue(null);
        }
    } else if (CmsFileUploadField.class.isAssignableFrom(field.getClass())) {
        // specific handling for file upload fields, because if they are filled out
        // they also shall be filled out if there are empty because there was an
        // other mandatory field not filled out or there was browsed through
        // different pages with the "prev" and the "next" buttons
        // here are also used hidden fields on the current page, that is why
        // it is possible that there are tow fields with the same name, one field
        // is the file upload field, the second one is the hidden field
        // the file upload field is the first one, the hidden field is the second one
        String[] parameterValues = m_parameterMap.get(field.getName());
        StringBuffer value = new StringBuffer();
        if (parameterValues != null) {
            if (parameterValues.length == 1) {
                // there file upload field value is empty, so take the hidden field value
                value.append(parameterValues[0]);
            } else {
                // there are two fields with the same name
                if (parameterValues[0].isEmpty()) {
                    // the file upload field is empty, so take the hidden field value
                    value.append(parameterValues[1]);
                } else {
                    // the file upload field is not empty, so take this value, because
                    // so the user choosed another file than before (in the hidden field)
                    value.append(parameterValues[0]);
                }
            }
        }
        field.setValue(value.toString());
    } else if (CmsDisplayField.class.isAssignableFrom(field.getClass())
            || CmsDisplayField.class.isAssignableFrom(field.getClass())) {
        String fieldValue = getDynamicFieldValue((CmsDynamicField) field);
        if (CmsStringUtil.isEmpty(fieldValue)) {
            // get field value from request for standard fields
            String[] parameterValues = m_parameterMap.get(field.getName());
            if (parameterValues != null) {
                fieldValue = parameterValues[0];
            }
        }
        field.setValue(fieldValue);
    } else if (CmsEmptyField.class.isAssignableFrom(field.getClass())) {
        String fieldValue = content.getStringValue(cms, inputFieldPath + NODE_FIELDDEFAULTVALUE, locale);
        field.setValue(fieldValue);
    } else if (!CmsTableField.class.isAssignableFrom(field.getClass())) {
        // get field value from request for standard fields
        String[] parameterValues = m_parameterMap.get(field.getName());
        StringBuffer value = new StringBuffer();
        if (parameterValues != null) {
            for (int j = 0; j < parameterValues.length; j++) {
                if (j != 0) {
                    value.append(", ");
                }
                value.append(parameterValues[j]);
            }
        }
        field.setValue(value.toString());
    }
    return field;
}

From source file:fr.paris.lutece.plugins.suggest.web.SuggestJspBean.java

/**
 * Get the request data and if there is no error insert the data in the suggest
 * specified in parameter. return null if there is no error or else return
 * the error page url/* w ww  .  j a  v  a 2 s . c o m*/
 *
 * @param request
 *            the request
 * @param suggest
 *            suggest
 *
 * @return null if there is no error or else return the error page url
 */
private String getSuggestData(MultipartHttpServletRequest request, Suggest suggest) {

    String strDefaultRole = AppPropertiesService.getProperty(PROPERTY_DEFAULT_ROLE_CODE);
    String strUpdateFile = request.getParameter(PARAMETER_UPDATE_FILE);
    String strTitle = request.getParameter(PARAMETER_TITLE);
    String strLibelleContribution = request.getParameter(PARAMETER_LIBELLE_CONTRIBUTION);
    String strUnavailabilityMessage = request.getParameter(PARAMETER_UNAVAILABILITY_MESSAGE);
    String strWorkgroup = request.getParameter(PARAMETER_WORKGROUP);
    String strIdVoteType = request.getParameter(PARAMETER_ID_VOTE_TYPE);
    String strActivePropositionState = request.getParameter(PARAMETER_ACTIVE_PROPOSITION_STATE);
    String strNumberVoteRequired = request.getParameter(PARAMETER_NUMBER_VOTE_REQUIRED);
    String strNumberDayRequired = request.getParameter(PARAMETER_NUMBER_DAY_REQUIRED);
    String strNumberSuggestSubmitInTopScore = request
            .getParameter(PARAMETER_NUMBER_SUGGEST_SUBMIT_IN_TOP_SCORE);
    String strNumberSuggestSubmitCaractersShown = request
            .getParameter(PARAMETER_NUMBER_SUGGEST_SUBMIT_CARACTERS_SHOWN);
    String strNumberSuggestSubmitInTopComment = request
            .getParameter(PARAMETER_NUMBER_SUGGEST_SUBMIT_IN_TOP_COMMENT);
    String strThemeXpage = request.getParameter(PARAMETER_THEME_XPAGE);

    String strActiveSuggestSubmitAuthentification = request
            .getParameter(PARAMETER_ACTIVE_SUGGEST_SUBMIT_AUTHENTIFICATION);
    String strActiveVoteAuthentification = request.getParameter(PARAMETER_ACTIVE_VOTE_AUTHENTIFICATION);
    String strActiveCommentAuthentification = request.getParameter(PARAMETER_ACTIVE_COMMENT_AUTHENTIFICATION);

    String strDisableNewSuggestSubmit = request.getParameter(PARAMETER_DISABLE_NEW_SUGGEST_SUBMIT);
    String strEnableMailNewSuggestSubmit = request.getParameter(PARAMETER_ENABLE_MAIL_NEW_SUGGEST_SUBMIT);
    String strIdMailingListSuggestSubmit = request.getParameter(PARAMETER_ID_MAILING_LIST_SUGGEST_SUBMIT);

    String strAuthorizedComment = request.getParameter(PARAMETER_AUTHORIZED_COMMENT);
    String strActiveEditorBbcode = request.getParameter(PARAMETER_ACTIVE_EDITOR_BBCODE_ON_COMMENT);
    String strDisableNewComment = request.getParameter(PARAMETER_DISABLE_NEW_COMMENT);
    String strLimitNumberVote = request.getParameter(PARAMETER_LIMIT_NUMBER_VOTE);
    String strActiveCaptcha = request.getParameter(PARAMETER_ACTIVE_CAPTCHA);
    String strLibelleValidateButton = request.getParameter(PARAMETER_LIBELLE_VALIDATE_BUTTON);
    String strShowCategoryBlock = request.getParameter(PARAMETER_SHOW_CATEGORY_BLOCK);
    String strShowTopScoreBlock = request.getParameter(PARAMETER_SHOW_TOP_SCORE_BLOCK);
    String strShowTopCommentBlock = request.getParameter(PARAMETER_SHOW_TOP_COMMENT_BLOCK);
    String strActiveSuggestSubmitPaginator = request.getParameter(PARAMETER_ACTIVE_SUGGEST_SUBMIT_PAGINATOR);
    String strNumberSuggestSubmitPerPage = request.getParameter(PARAMETER_NUMBER_SUGGEST_SUBMIT_PER_PAGE);
    String strRole = request.getParameter(PARAMETER_ROLE);
    String strHeader = request.getParameter(PARAMETER_HEADER);
    String strConfirmationMessage = request.getParameter(PARAMETER_CONFIRMATION_MESSAGE);
    String strIdDefaultSort = request.getParameter(PARAMETER_ID_DEFAULT_SORT);
    String strDisableVote = request.getParameter(PARAMETER_DISABLE_VOTE);
    String strDisplayCommentInSuggestSubmitList = request
            .getParameter(PARAMETER_DISPLAY_COMMENT_IN_SUGGEST_SUBMIT_LIST);
    String strNumberCommentDisplayInSuggestSubmitList = request
            .getParameter(PARAMETER_NUMBER_COMMENT_DISPLAY_IN_SUGGEST_SUBMIT_LIST);
    String strNumberCharCommentDisplayInSuggestSubmitList = request
            .getParameter(PARAMETER_NUMBER_CHAR_COMMENT_DISPLAY_IN_SUGGEST_SUBMIT_LIST);
    String strEnableMailNewCommentSubmit = request.getParameter(PARAMETER_ENABLE_MAIL_NEW_COMMENT_SUBMIT);
    String strEnableMailNewReportedSubmit = request.getParameter(PARAMETER_ENABLE_MAIL_NEW_REPORTED_SUBMIT);
    String strEnableTermsOfUse = request.getParameter(PARAMETER_ENABLE_TERMS_OF_USE);
    String strTermsOfUse = request.getParameter(PARAMETER_TERMS_OF_USE);
    String strEnableReports = request.getParameter(PARAMETER_ENABLE_REPORTS);
    String strDescription = request.getParameter(PARAMETER_DESCRIPTION);
    String strNotificationNewCommentSenderName = request
            .getParameter(PARAMETER_NOTIFICATION_NEW_COMMENT_SENDER_NAME);
    String strNotificationNewCommentTitle = request.getParameter(PARAMETER_NOTIFICATION_NEW_COMMENT_TITLE);
    String strNotificationNewCommentBody = request.getParameter(PARAMETER_NOTIFICATION_NEW_COMMENT_BODY);
    String strNotificationNewSuggestSubmitSenderName = request
            .getParameter(PARAMETER_NOTIFICATION_NEW_SUGGEST_SUBMIT_SENDER_NAME);
    String strNotificationNewSuggestSubmitTitle = request
            .getParameter(PARAMETER_NOTIFICATION_NEW_SUGGEST_SUBMIT_TITLE);
    String strNotificationNewSuggestSubmitBody = request
            .getParameter(PARAMETER_NOTIFICATION_NEW_SUGGEST_SUBMIT_BODY);

    int nIdVoteType = SuggestUtils.getIntegerParameter(strIdVoteType);
    int nIdMailingListSuggestSubmit = SuggestUtils.getIntegerParameter(strIdMailingListSuggestSubmit);
    int nNumberDayRequired = SuggestUtils.getIntegerParameter(strNumberDayRequired);
    int nNumberVoteRequired = SuggestUtils.getIntegerParameter(strNumberVoteRequired);
    int nNumberSuggestSubmitInTopScore = SuggestUtils.getIntegerParameter(strNumberSuggestSubmitInTopScore);
    int nNumberSuggestSubmitCaractersShown = SuggestUtils
            .getIntegerParameter(strNumberSuggestSubmitCaractersShown);
    int nNumberSuggestSubmitInTopComment = SuggestUtils.getIntegerParameter(strNumberSuggestSubmitInTopComment);
    int nNumberSuggestSubmitPerPage = SuggestUtils.getIntegerParameter(strNumberSuggestSubmitPerPage);
    int nIdDefaultSort = SuggestUtils.getIntegerParameter(strIdDefaultSort);
    int nNumberCommentDisplayInSuggestSubmitList = SuggestUtils
            .getIntegerParameter(strNumberCommentDisplayInSuggestSubmitList);
    int nNumberCharCommentDisplayInSuggestSubmitList = SuggestUtils
            .getIntegerParameter(strNumberCharCommentDisplayInSuggestSubmitList);

    String strFieldError = EMPTY_STRING;

    if (StringUtils.isEmpty(strTitle)) {
        strFieldError = FIELD_TITLE;
    }

    else if (StringUtils.isEmpty(strLibelleContribution)) {
        strFieldError = FIELD_LIBELLE_CONTRIBUTION;
    }

    else if (StringUtils.isEmpty(strUnavailabilityMessage)) {
        strFieldError = FIELD_UNAVAILABILITY_MESSAGE;
    } else if (nIdVoteType == -1) {
        strFieldError = FIELD_VOTE_TYPE;
    } else if (StringUtils.isEmpty(strNumberSuggestSubmitCaractersShown)) {
        strFieldError = FIELD_NUMBER_SUGGEST_SUBMIT_CARACTERS_SHOWN;
    } else if ((((strShowTopScoreBlock != null) && strShowTopScoreBlock.trim().equals(CONSTANTE_YES_VALUE))
            && (strNumberSuggestSubmitInTopScore == null))
            || strNumberSuggestSubmitInTopScore.trim().equals(EMPTY_STRING)) {
        strFieldError = FIELD_NUMBER_SUGGEST_SUBMIT_IN_TOP_SCORE;
    }

    else if (((strAuthorizedComment != null) && strAuthorizedComment.trim().equals(CONSTANTE_YES_VALUE))
            && ((strNumberSuggestSubmitInTopComment == null)
                    || strNumberSuggestSubmitInTopComment.trim().equals(EMPTY_STRING))) {
        strFieldError = FIELD_NUMBER_SUGGEST_SUBMIT_IN_TOP_COMMENT;
    }

    else if (((strActiveSuggestSubmitPaginator != null)
            && strActiveSuggestSubmitPaginator.trim().equals(CONSTANTE_YES_VALUE))
            && ((strNumberSuggestSubmitPerPage == null)
                    || strNumberSuggestSubmitPerPage.trim().equals(EMPTY_STRING))) {
        strFieldError = FIELD_NUMBER_SUGGEST_SUBMIT_PER_PAGE;
    }

    else if ((strLibelleValidateButton == null) || strLibelleValidateButton.trim().equals(EMPTY_STRING)) {
        strFieldError = FIELD_LIBELE_VALIDATE_BUTTON;
    } else if (((strDisplayCommentInSuggestSubmitList != null)
            && ((strNumberCommentDisplayInSuggestSubmitList == null)
                    || strNumberCommentDisplayInSuggestSubmitList.trim().equals(EMPTY_STRING)))) {
        strFieldError = FIELD_NUMBER_COMMENT_DISPLAY_IN_SUGGEST_SUBMIT_LIST;
    } else if (((strDisplayCommentInSuggestSubmitList != null)
            && ((strNumberCharCommentDisplayInSuggestSubmitList == null)
                    || strNumberCharCommentDisplayInSuggestSubmitList.trim().equals(EMPTY_STRING)))) {
        strFieldError = FIELD_NUMBER_CHAR_COMMENT_DISPLAY_IN_SUGGEST_SUBMIT_LIST;
    }

    else if (StringUtils.isEmpty(strNotificationNewCommentTitle)) {
        strFieldError = FIELD_NOTIFICATION_NEW_COMMENT_TITLE;

    } else if (StringUtils.isEmpty(strNotificationNewCommentBody)) {
        strFieldError = FIELD_NOTIFICATION_NEW_COMMENT_BODY;

    }

    else if (StringUtils.isEmpty(strNotificationNewSuggestSubmitTitle)) {

        strFieldError = FIELD_NOTIFICATION_NEW_SUGGEST_DUBMIT_TITLE;
    } else if (StringUtils.isEmpty(strNotificationNewSuggestSubmitBody)) {

        strFieldError = FIELD_NOTIFICATION_NEW_SUGGEST_DUBMIT_BODY;
    }

    if (!strFieldError.equals(EMPTY_STRING)) {
        Object[] tabRequiredFields = { I18nService.getLocalizedString(strFieldError, getLocale()) };

        return AdminMessageService.getMessageUrl(request, MESSAGE_MANDATORY_FIELD, tabRequiredFields,
                AdminMessage.TYPE_STOP);
    }

    if (nNumberSuggestSubmitCaractersShown < 0) {
        return AdminMessageService.getMessageUrl(request,
                MESSAGE_ILLOGICAL_NUMBER_SUGGEST_SUBMIT_CARACTERS_SHOWN, AdminMessage.TYPE_STOP);
    }

    if ((strNumberSuggestSubmitInTopScore != null)
            && !strNumberSuggestSubmitInTopScore.trim().equals(EMPTY_STRING)
            && (nNumberSuggestSubmitInTopScore < 0)) {
        return AdminMessageService.getMessageUrl(request, MESSAGE_ILLOGICAL_NUMBER_SUGGEST_SUBMIT_IN_TOP_SCORE,
                AdminMessage.TYPE_STOP);
    }

    if ((strActivePropositionState != null) && strActivePropositionState.trim().equals(CONSTANTE_YES_VALUE)
            && (strNumberVoteRequired != null) && !strNumberVoteRequired.trim().equals(EMPTY_STRING)
            && (nNumberVoteRequired < 0)) {
        return AdminMessageService.getMessageUrl(request, MESSAGE_ILLOGICAL_NUMBER_VOTE_REQUIRED,
                AdminMessage.TYPE_STOP);
    }

    if ((strNumberDayRequired != null) && !strNumberDayRequired.trim().equals(EMPTY_STRING)
            && (nNumberDayRequired < 0)) {
        return AdminMessageService.getMessageUrl(request, MESSAGE_ILLOGICAL_NUMBER_DAY_REQUIRED,
                AdminMessage.TYPE_STOP);
    }

    if ((strNumberSuggestSubmitInTopComment != null)
            && !strNumberSuggestSubmitInTopComment.trim().equals(EMPTY_STRING)
            && (nNumberSuggestSubmitInTopComment < 0)) {
        return AdminMessageService.getMessageUrl(request,
                MESSAGE_ILLOGICAL_NUMBER_SUGGEST_SUBMIT_IN_TOP_COMMENT, AdminMessage.TYPE_STOP);
    }

    if ((strNumberSuggestSubmitPerPage != null) && !strNumberSuggestSubmitPerPage.trim().equals(EMPTY_STRING)
            && (nNumberSuggestSubmitPerPage < 0)) {
        return AdminMessageService.getMessageUrl(request, MESSAGE_ILLOGICAL_NUMBER_SUGGEST_SUBMIT_PER_PAGE,
                AdminMessage.TYPE_STOP);
    }

    if ((strDisplayCommentInSuggestSubmitList != null) && (strNumberCommentDisplayInSuggestSubmitList != null)
            && !strNumberCommentDisplayInSuggestSubmitList.trim().equals(EMPTY_STRING)
            && (nNumberCommentDisplayInSuggestSubmitList < 0)) {
        return AdminMessageService.getMessageUrl(request,
                MESSAGE_ILLOGICAL_NUMBER_COMMENT_DISPLAY_IN_SUGGEST_SUBMIT_LIST, AdminMessage.TYPE_STOP);
    }

    if ((strDisplayCommentInSuggestSubmitList != null)
            && (strNumberCharCommentDisplayInSuggestSubmitList != null)
            && !strNumberCharCommentDisplayInSuggestSubmitList.trim().equals(EMPTY_STRING)
            && (nNumberCommentDisplayInSuggestSubmitList < 0)) {
        return AdminMessageService.getMessageUrl(request,
                MESSAGE_ILLOGICAL_NUMBER_CHAR_COMMENT_DISPLAY_IN_SUGGEST_SUBMIT_LIST, AdminMessage.TYPE_STOP);
    }

    suggest.setTitle(strTitle);
    suggest.setLibelleContribution(strLibelleContribution);
    suggest.setUnavailabilityMessage(strUnavailabilityMessage);
    suggest.setWorkgroup(strWorkgroup);

    if (suggest.getVoteType() == null) {
        suggest.setVoteType(new VoteType());
    }

    suggest.getVoteType().setIdVoteType(nIdVoteType);

    if ((strActivePropositionState != null) && strActivePropositionState.trim().equals(CONSTANTE_YES_VALUE)) {
        suggest.setActiveSuggestPropositionState(true);
        suggest.setNumberVoteRequired(nNumberVoteRequired);
    } else {
        suggest.setActiveSuggestPropositionState(false);
        suggest.setNumberVoteRequired(-1);
    }

    suggest.setNumberDayRequired(nNumberDayRequired);
    suggest.setActiveSuggestSubmitAuthentification(strActiveSuggestSubmitAuthentification != null);
    suggest.setActiveVoteAuthentification(strActiveVoteAuthentification != null);
    suggest.setActiveCommentAuthentification(strActiveCommentAuthentification != null);
    suggest.setActiveCaptcha(strActiveCaptcha != null);
    suggest.setDisableNewSuggestSubmit(strDisableNewSuggestSubmit != null);
    suggest.setEnableMailNewSuggestSubmit(strEnableMailNewSuggestSubmit != null);
    suggest.setEnableMailNewCommentSubmit(strEnableMailNewCommentSubmit != null);
    suggest.setEnableMailNewReportedSubmit(strEnableMailNewReportedSubmit != null);
    suggest.setIdMailingListSuggestSubmit(nIdMailingListSuggestSubmit);
    suggest.setAuthorizedComment(strAuthorizedComment != null);
    suggest.setDisableNewComment(strDisableNewComment != null);
    suggest.setActiveEditorBbcode(strActiveEditorBbcode != null);
    suggest.setLimitNumberVote(strLimitNumberVote != null);
    suggest.setShowCategoryBlock(strShowCategoryBlock != null);
    suggest.setShowTopScoreBlock(strShowTopScoreBlock != null);
    suggest.setShowTopCommentBlock(strShowTopCommentBlock != null);
    suggest.setActiveSuggestSubmitPaginator(strActiveSuggestSubmitPaginator != null);

    if (strThemeXpage != null) {
        suggest.setCodeTheme(strThemeXpage);
    }

    suggest.setLibelleValidateButton(strLibelleValidateButton);
    suggest.setNumberSuggestSubmitInTopScore(nNumberSuggestSubmitInTopScore);
    suggest.setNumberSuggestSubmitInTopComment(nNumberSuggestSubmitInTopComment);
    suggest.setNumberSuggestSubmitCaractersShown(nNumberSuggestSubmitCaractersShown);
    suggest.setNumberSuggestSubmitPerPage(nNumberSuggestSubmitPerPage);
    if (strDefaultRole != null && !strRole.equals(strDefaultRole)) {
        suggest.setRole(strRole);
    } else {
        suggest.setRole(null);
    }
    suggest.setHeader(strHeader);
    suggest.setConfirmationMessage(strConfirmationMessage);
    suggest.setIdDefaultSort(nIdDefaultSort);
    suggest.setDisableVote(strDisableVote != null);
    suggest.setDisplayCommentInSuggestSubmitList(strDisplayCommentInSuggestSubmitList != null);
    suggest.setNumberCommentDisplayInSuggestSubmitList(nNumberCommentDisplayInSuggestSubmitList);
    suggest.setNumberCharCommentDisplayInSuggestSubmitList(nNumberCharCommentDisplayInSuggestSubmitList);
    suggest.setEnableReports(strEnableReports != null);
    suggest.setEnableTermsOfUse(strEnableTermsOfUse != null);
    suggest.setTermsOfUse(strTermsOfUse);
    suggest.setDescription(strDescription);
    suggest.setNotificationNewCommentSenderName(strNotificationNewCommentSenderName);
    suggest.setNotificationNewCommentTitle(strNotificationNewCommentTitle);
    suggest.setNotificationNewCommentBody(strNotificationNewCommentBody);
    suggest.setNotificationNewSuggestSubmitSenderName(strNotificationNewSuggestSubmitSenderName);
    suggest.setNotificationNewSuggestSubmitTitle(strNotificationNewSuggestSubmitTitle);
    suggest.setNotificationNewSuggestSubmitBody(strNotificationNewSuggestSubmitBody);

    if ((suggest.getIdSuggest() == SuggestUtils.CONSTANT_ID_NULL) || (strUpdateFile != null)) {
        FileItem imageSource = request.getFile(PARAMETER_IMAGE_SOURCE);
        String strImageName = FileUploadService.getFileNameOnly(imageSource);

        ImageResource image = new ImageResource();
        byte[] baImageSource = imageSource.get();

        if ((strImageName != null) && !strImageName.equals("")) {
            image.setImage(baImageSource);
            image.setMimeType(imageSource.getContentType());
        }

        suggest.setImage(image);
    }

    return null; // No error
}

From source file:com.hiperf.common.ui.server.storage.impl.PersistenceHelper.java

@Override
public Object saveFile(String fileClass, String fileNameField, String fileStorageField, String fileName,
        FileItem item) throws PersistenceException {
    getIdFieldFromFileStorageClass(fileClass);
    TransactionContext tc = null;/*from   w  ww.  j  a  v  a  2  s .  c  om*/
    try {
        tc = createTransactionalContext();
        EntityManager em = tc.getEm();
        ITransaction tx = tc.getTx();
        tx.begin();
        Class clazz = Class.forName(fileClass);
        Object o = clazz.newInstance();
        for (PropertyDescriptor pd : propertyDescriptorsByClassName.get(fileClass)) {
            if (fileNameField.equals(pd.getName())) {
                pd.getWriteMethod().invoke(o, fileName);
            } else if (fileStorageField.equals(pd.getName())) {
                pd.getWriteMethod().invoke(o, item.get());
            }
        }
        em.persist(o);
        tx.commit();
        return idsByClassName.get(fileClass).iterator().next().getReadMethod().invoke(o, new Object[0]);
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Exception in saveFile : " + e.getMessage(), e);
        try {
            if (tc != null)
                tc.rollback();
        } catch (Exception ee) {
        }
        throw new PersistenceException(e.getMessage(), e);
    } finally {
        if (tc != null)
            close(tc);
    }

}

From source file:fr.paris.lutece.plugins.plu.web.PluJspBean.java

/**
 * Add a file in _fileList/* w  w  w . j a v  a 2  s .  c  o m*/
 * @param request HttpServletRequest
 * @return ret errorMessage
 */
private String addFileToFileList(HttpServletRequest request) {
    String ret = "";
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

    FileItem fileItem = multipartRequest.getFile(PARAMETER_FILE);

    if ((StringUtils.isNotEmpty(request.getParameter(PARAMETER_FILE_TITLE)))
            && (StringUtils.isNotEmpty(request.getParameter(PARAMETER_FILE_NAME)))
            && (fileItem.get() != null)) {
        File file = new File();
        PhysicalFile physicalFile = new PhysicalFile();
        physicalFile.setValue(fileItem.get());

        String name = fileItem.getName();
        String type = name.substring(name.lastIndexOf(".") + 1).toUpperCase();

        //Search files with same name
        int nNumVersion = Integer.parseInt(request.getParameter(PARAMETER_VERSION_NUM));
        String strFileDBName = PluUtils.getFileNameForDB(request.getParameter(PARAMETER_FILE_NAME),
                String.valueOf(nNumVersion));
        FileFilter fileFilter = new FileFilter();
        fileFilter.setName(strFileDBName);
        List<File> listFileByName = _fileServices.findByFilter(fileFilter, new AtomeFilter());

        //If a file with the same name exist in DB or a new atome file have the same name : error
        if (!listFileByName.isEmpty()) {
            Object[] args = { "", request.getParameter(PARAMETER_FILE_NAME) };
            ret = this.getMessageJsp(request, MESSAGE_ERROR_FILE_CREATE_NAME, args,
                    "jsp/admin/plugins/plu/file/JoinFile.jsp", null);
        }
        for (File fileTest : _fileList) {
            if (fileTest.getName().equals(request.getParameter(PARAMETER_FILE_NAME))) {
                Object[] args = { "", request.getParameter(PARAMETER_FILE_NAME) };
                ret = this.getMessageJsp(request, MESSAGE_ERROR_FILE_CREATE_NAME, args,
                        "jsp/admin/plugins/plu/file/JoinFile.jsp", null);
            }
        }
        if (StringUtils.isEmpty(ret)) {
            file.setName(request.getParameter(PARAMETER_FILE_NAME).replace(" ", "-"));
            file.setTitle(request.getParameter(PARAMETER_FILE_TITLE));
            file.setUtilisation(request.getParameter(PARAMETER_FILE_UTILISATION).charAt(0));
            file.setFile(physicalFile.getValue());
            file.setMimeType(type);
            file.setSize((int) fileItem.getSize());
            _fileList.add(file);
        }
    } else if (StringUtils.isNotEmpty(request.getParameter("joinFile"))) {
        if (request.getParameter("joinFile").equals("true")) {
            ret = this.getMessageJsp(request, MESSAGE_ERROR_REQUIRED_FIELD, null,
                    "jsp/admin/plugins/plu/file/JoinFile.jsp", null);
        }
    }

    return ret;
}

From source file:importer.handler.post.ImporterPostHandler.java

/**
 * Parse the import params from the request
 * @param request the http request/*from   w  w  w.ja  va 2 s .com*/
 */
void parseImportParams(HttpServletRequest request) throws AeseException {
    try {
        FileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // Parse the request
        List items = upload.parseRequest(request);
        for (int i = 0; i < items.size(); i++) {
            FileItem item = (FileItem) items.get(i);
            if (item.isFormField()) {
                String fieldName = item.getFieldName();
                if (fieldName != null) {
                    String contents = item.getString();
                    if (fieldName.equals(Params.DOCID)) {
                        if (contents.startsWith("/")) {
                            contents = contents.substring(1);
                            int pos = contents.indexOf("/");
                            if (pos != -1) {
                                database = contents.substring(0, pos);
                                contents = contents.substring(pos + 1);
                            }
                        }
                        docid = contents;
                    } else if (fieldName.startsWith(Params.SHORT_VERSION))
                        nameMap.put(fieldName.substring(Params.SHORT_VERSION.length()), item.getString());
                    else if (fieldName.equals(Params.LC_STYLE) || fieldName.equals(Params.STYLE)
                            || fieldName.equals(Params.CORFORM)) {
                        jsonKeys.put(fieldName.toLowerCase(), contents);
                        style = contents;
                    } else if (fieldName.equals(Params.DEMO)) {
                        if (contents != null && contents.equals("brillig"))
                            demo = false;
                        else
                            demo = true;
                    } else if (fieldName.equals(Params.TITLE))
                        title = contents;
                    else if (fieldName.equals(Params.FILTER))
                        filterName = contents.toLowerCase();
                    else if (fieldName.equals(Params.SIMILARITY))
                        similarityTest = contents != null && contents.equals("1");
                    else if (fieldName.equals(Params.SPLITTER))
                        splitterName = contents;
                    else if (fieldName.equals(Params.STRIPPER))
                        stripperName = contents;
                    else if (fieldName.equals(Params.TEXT))
                        textName = contents.toLowerCase();
                    else if (fieldName.equals(Params.DICT))
                        dict = contents;
                    else if (fieldName.equals(Params.ENCODING))
                        encoding = contents;
                    else if (fieldName.equals(Params.HH_EXCEPTIONS))
                        hhExceptions = contents;
                    else
                        jsonKeys.put(fieldName, contents);
                }
            } else if (item.getName().length() > 0) {
                try {
                    // assuming that the contents are text
                    //item.getName retrieves the ORIGINAL file name
                    String type = item.getContentType();
                    if (type != null && type.startsWith("image/")) {
                        InputStream is = item.getInputStream();
                        ByteHolder bh = new ByteHolder();
                        while (is.available() > 0) {
                            byte[] b = new byte[is.available()];
                            is.read(b);
                            bh.append(b);
                        }
                        ImageFile iFile = new ImageFile(item.getName(), item.getContentType(), bh.getData());
                        images.add(iFile);
                    } else {
                        byte[] rawData = item.get();
                        guessEncoding(rawData);
                        //System.out.println(encoding);
                        File f = new File(item.getName(), new String(rawData, encoding));
                        files.add(f);
                    }
                } catch (Exception e) {
                    throw new AeseException(e);
                }
            }
        }
        if (style == null)
            style = DEFAULT_STYLE;
    } catch (Exception e) {
        throw new AeseException(e);
    }
}

From source file:calliope.handler.post.AeseImportHandler.java

/**
 * Parse the import params from the request
 * @param request the http request/*from w ww.  j a  v a 2s . c  o  m*/
 */
void parseImportParams(HttpServletRequest request) throws AeseException {
    try {
        FileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // Parse the request
        List items = upload.parseRequest(request);
        for (int i = 0; i < items.size(); i++) {
            FileItem item = (FileItem) items.get(i);
            if (item.isFormField()) {
                String fieldName = item.getFieldName();
                if (fieldName != null) {
                    String contents = item.getString();
                    if (fieldName.equals(Params.DOCID)) {
                        if (contents.startsWith("/")) {
                            contents = contents.substring(1);
                            int pos = contents.indexOf("/");
                            if (pos != -1) {
                                database = contents.substring(0, pos);
                                contents = contents.substring(pos + 1);
                            }
                        }
                        docID = new DocID(contents);
                    } else if (fieldName.startsWith(Params.SHORT_VERSION))
                        nameMap.put(fieldName.substring(Params.SHORT_VERSION.length()), item.getString());
                    else if (fieldName.equals(Params.LC_STYLE) || fieldName.equals(Params.STYLE)) {
                        jsonKeys.put(fieldName.toLowerCase(), contents);
                        style = contents;
                    } else if (fieldName.equals(Params.DEMO)) {
                        if (contents != null && contents.equals("brillig"))
                            demo = false;
                        else
                            demo = true;
                    } else if (fieldName.equals(Params.TITLE))
                        title = contents;
                    else if (fieldName.equals(Params.FILTER))
                        filterName = contents.toLowerCase();
                    else if (fieldName.equals(Params.SIMILARITY))
                        similarityTest = contents != null && contents.equals("1");
                    else if (fieldName.equals(Params.SPLITTER))
                        splitterName = contents;
                    else if (fieldName.equals(Params.STRIPPER))
                        stripperName = contents;
                    else if (fieldName.equals(Params.TEXT))
                        textName = contents.toLowerCase();
                    else if (fieldName.equals(Params.XSLT))
                        xslt = getConfig(Config.xslt, contents);
                    else if (fieldName.equals(Params.DICT))
                        dict = contents;
                    else if (fieldName.equals(Params.ENCODING))
                        encoding = contents;
                    else if (fieldName.equals(Params.HH_EXCEPTIONS))
                        hhExceptions = contents;
                    else
                        jsonKeys.put(fieldName, contents);
                }
            } else if (item.getName().length() > 0) {
                try {
                    // assuming that the contents are text
                    //item.getName retrieves the ORIGINAL file name
                    String type = item.getContentType();
                    if (type != null && type.startsWith("image/")) {
                        InputStream is = item.getInputStream();
                        ByteHolder bh = new ByteHolder();
                        while (is.available() > 0) {
                            byte[] b = new byte[is.available()];
                            is.read(b);
                            bh.append(b);
                        }
                        ImageFile iFile = new ImageFile(item.getName(), item.getContentType(), bh.getData());
                        images.add(iFile);
                    } else {
                        byte[] rawData = item.get();
                        guessEncoding(rawData);
                        //System.out.println(encoding);
                        File f = new File(item.getName(), new String(rawData, encoding));
                        files.add(f);
                    }
                } catch (Exception e) {
                    throw new AeseException(e);
                }
            }
        }
        if (style == null)
            style = DEFAULT_STYLE;
    } catch (Exception e) {
        throw new AeseException(e);
    }
    //        System.out.println("Import params received:");
    //        System.out.println("docID="+docID.get());
    //        System.out.println("style="+style);
    //        System.out.println("filterName="+filterName);
    //        System.out.println("database="+database);
    //        System.out.println("splitterName="+splitterName);
    //        System.out.println("stripperName="+stripperName);
    //        System.out.println("encoding="+encoding);
    //        System.out.println("hhExceptions="+hhExceptions);
    //        System.out.println("similarityTest="+similarityTest);
    //        System.out.println("dict="+dict);
    //        System.out.println("xslt="+xslt);
    //        System.out.println("demo="+demo);
    //        System.out.println("textName="+textName);
}