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:org.opencms.frontend.templateone.form.CmsForm.java

/**
 * Initializes the field objects of the form.<p>
 * //from w w  w . j  a v a 2 s . c o  m
 * @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 initial if true, field values are filled with values specified in the XML configuration, otherwise values are read from the request
 * @throws CmsConfigurationException if parsing the configuration fails 
 */
private void initInputFields(CmsXmlContent content, CmsJspActionElement jsp, Locale locale,
        CmsMessages messages, boolean initial) throws CmsConfigurationException {

    CmsObject cms = jsp.getCmsObject();
    List fieldValues = content.getValues(NODE_INPUTFIELD, locale);
    int fieldValueSize = fieldValues.size();
    CmsFieldFactory fieldFactory = CmsFieldFactory.getSharedInstance();
    Map fileUploads = (Map) jsp.getRequest().getSession().getAttribute(CmsFormHandler.ATTRIBUTE_FILEITEMS);

    for (int i = 0; i < fieldValueSize; i++) {
        I_CmsXmlContentValue inputField = (I_CmsXmlContentValue) fieldValues.get(i);
        String inputFieldPath = inputField.getPath() + "/";
        A_CmsField field = null;

        // get the field from the factory for the specified type
        String stringValue = content.getStringValue(cms, inputFieldPath + NODE_FIELDTYPE, locale);
        field = fieldFactory.getField(stringValue);

        // create the field name
        field.setName(inputFieldPath.substring(0, inputFieldPath.length() - 1));
        // get the field label
        stringValue = content.getStringValue(cms, inputFieldPath + NODE_FIELDLABEL, locale);
        field.setLabel(getConfigurationValue(stringValue, ""));
        // validation error message
        stringValue = content.getStringValue(cms, inputFieldPath + NODE_FIELDERRORMESSAGE, locale);
        field.setErrorMessage(stringValue);
        // get the field value
        if (initial && CmsStringUtil.isEmpty(getParameter(field.getName()))) {
            // only fill in values from configuration file if called initially
            String fieldValue = content.getStringValue(cms, inputFieldPath + NODE_FIELDDEFAULTVALUE, locale);
            if (CmsStringUtil.isNotEmpty(fieldValue)) {
                CmsMacroResolver resolver = CmsMacroResolver.newInstance().setCmsObject(cms)
                        .setJspPageContext(jsp.getJspContext());
                field.setValue(resolver.resolveMacros(fieldValue));
            }
        } else {
            // get field value from request for standard fields
            String[] parameterValues = (String[]) 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());
        }

        // 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 = (FileItem) 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);
            }

            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                       
                    StringTokenizer T = new StringTokenizer(fieldValue, "|");
                    List items = new ArrayList(T.countTokens());
                    while (T.hasMoreTokens()) {
                        String part = T.nextToken();
                        // check preselection 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()));
                    }
                    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()));
                }
            }
        }

        addField(field);
    }

    // validate the form configuration
    validateFormConfiguration(messages);

    if (isConfirmationMailEnabled() && isConfirmationMailOptional()) {

        // add the checkbox to activate confirmation mail for customer
        I_CmsField confirmationMailCheckbox = createConfirmationMailCheckbox(messages, initial);
        addField(confirmationMailCheckbox);
    }
}

From source file:org.opencms.frontend.templateone.form.CmsFormHandler.java

/**
 * Sends the mail with the form data to the specified recipients.<p>
 * //from w  ww.  j  a v 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
 */
public boolean sendMail() {

    try {
        // send optional confirmation mail
        if (getFormConfiguration().isConfirmationMailEnabled()) {
            if (!getFormConfiguration().isConfirmationMailOptional()
                    || Boolean.valueOf(getParameter(CmsForm.PARAM_SENDCONFIRMATION)).booleanValue()) {
                sendConfirmationMail();
            }
        }
        // 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())) {
                theMail.setFrom(getFormConfiguration().getMailFrom());
            }
            theMail.setTo(createInternetAddresses(getFormConfiguration().getMailTo()));
            theMail.setCc(createInternetAddresses(getFormConfiguration().getMailCC()));
            theMail.setBcc(createInternetAddresses(getFormConfiguration().getMailBCC()));
            theMail.setSubject(
                    getFormConfiguration().getMailSubjectPrefix() + getFormConfiguration().getMailSubject());
            theMail.setHtmlMsg(createMailTextFromFields(true, false));
            theMail.setTextMsg(createMailTextFromFields(false, false));

            // attach file uploads
            Map fileUploads = (Map) getRequest().getSession().getAttribute(ATTRIBUTE_FILEITEMS);
            Iterator i = fileUploads.values().iterator();
            while (i.hasNext()) {
                FileItem attachment = (FileItem) 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())) {
                theMail.setFrom(getFormConfiguration().getMailFrom());
            }
            theMail.setTo(createInternetAddresses(getFormConfiguration().getMailTo()));
            theMail.setCc(createInternetAddresses(getFormConfiguration().getMailCC()));
            theMail.setBcc(createInternetAddresses(getFormConfiguration().getMailBCC()));
            theMail.setSubject(
                    getFormConfiguration().getMailSubjectPrefix() + getFormConfiguration().getMailSubject());
            theMail.setMsg(createMailTextFromFields(false, false));
            // send the mail
            theMail.send();
        }
    } catch (Exception e) {
        // an error occurred during mail creation
        if (LOG.isErrorEnabled()) {
            LOG.error(e.getLocalizedMessage(), e);
        }
        m_errors.put("sendmail", e.getMessage());
        return false;
    }
    return true;
}

From source file:org.opencms.workplace.administration.A_CmsImportFromHttp.java

/**
 * Gets a database import file from the client and copies it to the server.<p>
 *
 * @param destination the destination of the file on the server
 * //from  ww  w . j a  v a  2  s  .c  o  m
 * @return the name of the file or null if something went wrong when importing the file
 * 
 * @throws CmsIllegalArgumentException if the specified file name is invalid
 * @throws CmsRfsException if generating folders or files on the server fails
 */
protected String copyFileToServer(String destination) throws CmsIllegalArgumentException, CmsRfsException {

    // get the file item from the multipart request
    Iterator i = getMultiPartFileItems().iterator();
    FileItem fi = null;
    while (i.hasNext()) {
        fi = (FileItem) i.next();
        if (fi.getName() != null) {
            // found the file object, leave iteration
            break;
        } else {
            // this is no file object, check next item
            continue;
        }
    }

    String fileName = null;

    if ((fi != null) && CmsStringUtil.isNotEmptyOrWhitespaceOnly(fi.getName())) {
        // file name has been specified, upload the file
        fileName = fi.getName();
        byte[] content = fi.get();
        fi.delete();
        // get the file name without folder information
        fileName = CmsResource.getName(fileName.replace('\\', '/'));
        // first create the folder if it does not exist
        File discFolder = new File(OpenCms.getSystemInfo().getAbsoluteRfsPathRelativeToWebInf(
                OpenCms.getSystemInfo().getPackagesRfsPath() + File.separator));
        if (!discFolder.exists()) {
            if (!discFolder.mkdir()) {
                throw new CmsRfsException(Messages.get().container(Messages.ERR_FOLDER_NOT_CREATED_0));
            }
        }
        // write the file into the packages folder of the OpenCms server
        File discFile = new File(OpenCms.getSystemInfo()
                .getAbsoluteRfsPathRelativeToWebInf(destination + File.separator + fileName));
        try {
            // write the new file to disk
            OutputStream s = new FileOutputStream(discFile);
            s.write(content);
            s.close();
        } catch (FileNotFoundException e) {
            throw new CmsRfsException(Messages.get().container(Messages.ERR_FILE_NOT_FOUND_1, fileName, e));
        } catch (IOException e) {
            throw new CmsRfsException(Messages.get().container(Messages.ERR_FILE_NOT_WRITTEN_0, e));
        }
    } else {
        // no file name has been specified, throw exception
        throw new CmsIllegalArgumentException(Messages.get().container(Messages.ERR_FILE_NOT_SPECIFIED_0));
    }
    // set the request parameter to the name of the import file
    setParamImportfile(fileName);
    return fileName;
}

From source file:org.opencms.workplace.commons.CmsReplace.java

/**
 * Uploads the specified file and replaces the VFS file.<p>
 * /*from www. ja va 2  s. com*/
 * @throws JspException if inclusion of error dialog fails
 */
public void actionReplace() throws JspException {

    try {
        // get the file item from the multipart request
        Iterator i = getMultiPartFileItems().iterator();
        FileItem fi = null;
        while (i.hasNext()) {
            fi = (FileItem) i.next();
            if (fi.getName() != null) {
                // found the file object, leave iteration
                break;
            }
        }

        if (fi != null) {
            // get file object information
            long size = fi.getSize();
            long maxFileSizeBytes = OpenCms.getWorkplaceManager().getFileBytesMaxUploadSize(getCms());
            // check file size
            if ((maxFileSizeBytes > 0) && (size > maxFileSizeBytes)) {
                // file size is larger than maximum allowed file size, throw an error
                throw new CmsException(Messages.get().container(Messages.ERR_FILE_SIZE_TOO_LARGE_1,
                        new Long((maxFileSizeBytes / 1024))));
            }
            byte[] content = fi.get();
            fi.delete();

            // determine the resource type id from the resource to replace
            CmsResource res = getCms().readResource(getParamResource(), CmsResourceFilter.IGNORE_EXPIRATION);
            CmsFile file = getCms().readFile(res);
            byte[] contents = file.getContents();
            int resTypeId = res.getTypeId();
            // check the lock state and replace resource
            checkLock(getParamResource());
            try {
                getCms().replaceResource(getParamResource(), resTypeId, content, null);
            } catch (CmsDbSqlException sqlExc) {
                // SQL error, probably the file is too large for the database settings, restore old content
                file.setContents(contents);
                getCms().writeFile(file);
                throw sqlExc;
            }
            // close dialog
            actionCloseDialog();
        } else {
            throw new CmsException(Messages.get().container(Messages.ERR_UPLOAD_FILE_NOT_FOUND_0));
        }
    } catch (Throwable e) {
        // error replacing file, show error dialog
        includeErrorpage(this, e);
    }
}

From source file:org.opencms.workplace.explorer.CmsNewCsvFile.java

/**
 * Returns the content of the file upload and sets the resource name.<p>
 * //from  w w  w  .  j  a va2  s .co  m
 * @return the byte content of the uploaded file
 * @throws CmsWorkplaceException if the filesize if greater that maxFileSizeBytes or if the upload file cannot be found
 */
public byte[] getFileContentFromUpload() throws CmsWorkplaceException {

    byte[] content;
    // get the file item from the multipart request
    Iterator i = getMultiPartFileItems().iterator();
    FileItem fi = null;
    while (i.hasNext()) {
        fi = (FileItem) i.next();
        if (fi.getName() != null) {
            // found the file object, leave iteration
            break;
        } else {
            // this is no file object, check next item
            continue;
        }
    }

    if (fi != null) {
        long size = fi.getSize();
        if (size == 0) {
            throw new CmsWorkplaceException(Messages.get().container(Messages.ERR_UPLOAD_FILE_NOT_FOUND_0));
        }
        long maxFileSizeBytes = OpenCms.getWorkplaceManager().getFileBytesMaxUploadSize(getCms());
        // check file size
        if ((maxFileSizeBytes > 0) && (size > maxFileSizeBytes)) {
            throw new CmsWorkplaceException(Messages.get().container(Messages.ERR_UPLOAD_FILE_SIZE_TOO_HIGH_1,
                    new Long(maxFileSizeBytes / 1024)));
        }
        content = fi.get();
        fi.delete();
        setParamResource(fi.getName());

    } else {
        throw new CmsWorkplaceException(Messages.get().container(Messages.ERR_UPLOAD_FILE_NOT_FOUND_0));
    }
    return content;
}

From source file:org.opencms.workplace.explorer.CmsNewResourceUpload.java

/**
 * Uploads the specified file and unzips it, if selected.<p>
 * /*from   w ww .  j  a  v  a2s . co  m*/
 * @throws JspException if inclusion of error dialog fails
 */
public void actionUpload() throws JspException {

    // determine the type of upload
    boolean unzipFile = Boolean.valueOf(getParamUnzipFile()).booleanValue();
    // Suffix for error messages (e.g. when exceeding the maximum file upload size)
    if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(getParamClientFolder())) {
        CmsUserSettings userSettings = new CmsUserSettings(getCms());
        userSettings.setUploadAppletClientFolder(getParamClientFolder());
        try {
            userSettings.save(getCms());
        } catch (CmsException e) {
            // it's not fatal if the client folder for the applet file chooser is not possible 
            if (LOG.isErrorEnabled()) {
                LOG.error(Messages.get().getBundle(getLocale()).key(Messages.ERR_UPLOAD_STORE_CLIENT_FOLDER_1,
                        new Object[] { getCms().getRequestContext().getCurrentUser().getName() }), e);
            }
        }
    }

    try {
        // get the file item from the multipart request
        Iterator i = getMultiPartFileItems().iterator();
        FileItem fi = null;
        while (i.hasNext()) {
            fi = (FileItem) i.next();
            if (fi.getName() != null) {
                // found the file object, leave iteration
                break;
            } else {
                // this is no file object, check next item
                continue;
            }
        }

        if (fi != null) {
            String fileName = fi.getName();
            long size = fi.getSize();
            long maxFileSizeBytes = OpenCms.getWorkplaceManager().getFileBytesMaxUploadSize(getCms());
            // check file size
            if ((maxFileSizeBytes > 0) && (size > maxFileSizeBytes)) {
                // file size is larger than maximum allowed file size, throw an error
                throw new CmsWorkplaceException(Messages.get().container(
                        Messages.ERR_UPLOAD_FILE_SIZE_TOO_HIGH_1, new Long(maxFileSizeBytes / 1024)));
            }
            byte[] content = fi.get();
            fi.delete();

            if (unzipFile) {
                // zip file upload
                String currentFolder = getParamUploadFolder();
                if (CmsStringUtil.isEmpty(currentFolder)) {
                    // no upload folder parameter found, get current folder
                    currentFolder = getParamCurrentFolder();
                }
                if (CmsStringUtil.isEmpty(currentFolder) || !currentFolder.startsWith("/")) {
                    // no folder information found, guess upload folder
                    currentFolder = computeCurrentFolder();
                }
                // import the zip contents
                new CmsImportFolder(content, currentFolder, getCms(), false);

            } else {
                // single file upload
                String newResname = CmsResource.getName(fileName.replace('\\', '/'));
                // determine Title property value to set on new resource
                String title = newResname;
                if (title.lastIndexOf('.') != -1) {
                    title = title.substring(0, title.lastIndexOf('.'));
                }
                List properties = new ArrayList(1);
                CmsProperty titleProp = new CmsProperty();
                titleProp.setName(CmsPropertyDefinition.PROPERTY_TITLE);
                if (OpenCms.getWorkplaceManager().isDefaultPropertiesOnStructure()) {
                    titleProp.setStructureValue(title);
                } else {
                    titleProp.setResourceValue(title);
                }
                properties.add(titleProp);
                newResname = getCms().getRequestContext().getFileTranslator().translateResource(newResname);
                setParamNewResourceName(newResname);
                setParamResource(newResname);
                setParamResource(computeFullResourceName());
                // determine the resource type id from the given information
                int resTypeId = OpenCms.getResourceManager().getDefaultTypeForName(newResname).getTypeId();
                int plainId = OpenCms.getResourceManager()
                        .getResourceType(CmsResourceTypePlain.getStaticTypeName()).getTypeId();
                if (!getCms().existsResource(getParamResource(), CmsResourceFilter.IGNORE_EXPIRATION)) {
                    try {
                        // create the resource
                        getCms().createResource(getParamResource(), resTypeId, content, properties);
                    } catch (CmsSecurityException e) {
                        // in case of not enough permissions, try to create a plain text file
                        getCms().createResource(getParamResource(), plainId, content, properties);
                    } catch (CmsDbSqlException sqlExc) {
                        // SQL error, probably the file is too large for the database settings, delete file
                        getCms().lockResource(getParamResource());
                        getCms().deleteResource(getParamResource(), CmsResource.DELETE_PRESERVE_SIBLINGS);
                        throw sqlExc;
                    }
                } else {
                    checkLock(getParamResource());
                    CmsFile file = getCms().readFile(getParamResource(), CmsResourceFilter.IGNORE_EXPIRATION);
                    byte[] contents = file.getContents();
                    try {
                        getCms().replaceResource(getParamResource(), resTypeId, content, null);
                    } catch (CmsSecurityException e) {
                        // in case of not enough permissions, try to create a plain text file
                        getCms().replaceResource(getParamResource(), plainId, content, null);
                    } catch (CmsDbSqlException sqlExc) {
                        // SQL error, probably the file is too large for the database settings, restore content
                        file.setContents(contents);
                        getCms().writeFile(file);
                        throw sqlExc;
                    }
                }
            }
        } else {
            throw new CmsWorkplaceException(Messages.get().container(Messages.ERR_UPLOAD_FILE_NOT_FOUND_0));
        }
    } catch (Throwable e) {
        // error uploading file, show error dialog
        setParamMessage(Messages.get().getBundle(getLocale()).key(Messages.ERR_UPLOAD_FILE_0));
        setAction(ACTION_SHOWERROR);
        includeErrorpage(this, e);
    }
}

From source file:org.opencms.workplace.tools.accounts.CmsUserDataImportDialog.java

/**
 * @see org.opencms.workplace.tools.accounts.A_CmsUserDataImexportDialog#actionCommit()
 *///from  ww  w.  j  ava2  s  . c om
public void actionCommit() throws IOException, ServletException {

    List errors = new ArrayList();

    // get the file item from the multipart request
    Iterator it = getMultiPartFileItems().iterator();
    FileItem fi = null;
    while (it.hasNext()) {
        fi = (FileItem) it.next();
        if (fi.getName() != null) {
            // found the file object, leave iteration
            break;
        } else {
            // this is no file object, check next item
            continue;
        }
    }

    if (fi != null && CmsStringUtil.isNotEmptyOrWhitespaceOnly(fi.getName())) {
        byte[] content = fi.get();
        File importFile = File.createTempFile("import_users", ".csv");
        m_importFile = importFile.getAbsolutePath();

        FileOutputStream fileOutput = new FileOutputStream(importFile);
        fileOutput.write(content);
        fileOutput.close();
        fi.delete();

        FileReader fileReader = new FileReader(importFile);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        String line = bufferedReader.readLine();

        if (line != null) {
            List colDefs = CmsStringUtil.splitAsList(line, CmsXsltUtil.getPreferredDelimiter(line));
            if (!colDefs.contains("name")) {
                errors.add(new CmsRuntimeException(
                        Messages.get().container(Messages.ERR_USERDATA_IMPORT_CSV_MISSING_NAME_0)));
            }
            if ((line.indexOf("password") == -1) && CmsStringUtil.isEmptyOrWhitespaceOnly(m_password)) {
                errors.add(new CmsRuntimeException(
                        Messages.get().container(Messages.ERR_USERDATA_IMPORT_CSV_MISSING_PASSWORD_0)));
            }
        }
        bufferedReader.close();
    } else {
        errors.add(new CmsIllegalArgumentException(
                Messages.get().container(Messages.ERR_USERDATA_IMPORT_NO_CONTENT_0)));
    }

    if (errors.isEmpty()) {
        Map params = new HashMap();
        params.put("groups", CmsStringUtil.collectionAsString(getGroups(), ","));
        params.put("roles", CmsStringUtil.collectionAsString(getRoles(), ","));
        params.put("importfile", m_importFile);
        params.put("password", m_password);
        params.put(A_CmsOrgUnitDialog.PARAM_OUFQN, getParamOufqn());
        // set action parameter to initial dialog call
        params.put(CmsDialog.PARAM_ACTION, CmsDialog.DIALOG_INITIAL);

        getToolManager().jspForwardTool(this, getCurrentToolPath() + "/list", params);
    }
    // set the list of errors to display when something goes wrong
    setCommitErrors(errors);
}

From source file:org.opencms.workplace.tools.database.CmsHtmlImportDialog.java

/**
 * This function reads the file item and if its exits then the 
 * file is saved in the temporary directory of the system.<p>
 * //from w ww.  j  av a  2 s .c  om
 * @param fi the file item from the multipart-request
 * 
 * @throws CmsException if something goes wrong.
 */
private void writeHttpImportDir(FileItem fi) throws CmsException {

    try {

        if (fi != null && CmsStringUtil.isNotEmptyOrWhitespaceOnly(fi.getName())) {
            //write the file in the tmp-directory of the system
            byte[] content = fi.get();
            File importFile = File.createTempFile("import_html", ".zip");
            //write the content in the tmp file
            FileOutputStream fileOutput = new FileOutputStream(importFile.getAbsolutePath());
            fileOutput.write(content);
            fileOutput.close();
            fi.delete();
            m_htmlimport.setHttpDir(importFile.getAbsolutePath());
        }
    } catch (Exception e) {
        throw new CmsException(Messages.get().container(Messages.ERR_ACTION_ZIPFILE_UPLOAD_0));
    }
}

From source file:org.openempi.webapp.server.FileUploadServlet.java

@SuppressWarnings("unchecked")
@Override//from   w  w  w . j a v  a  2  s  . c om
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    String message = "success";
    // process only multipart requests
    if (ServletFileUpload.isMultipartContent(req)) {

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

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

        // Parse the request
        try {
            List<FileItem> items = upload.parseRequest(req);
            String name = null;
            for (FileItem item : items) {
                // Store field names
                if (item.isFormField()) {
                    if (item.getFieldName().equals("name")) {
                        name = new String(item.get());
                    }
                    continue;
                }

                String fileName = item.getName();
                // get only the file name not whole path
                if (fileName != null) {
                    fileName = FilenameUtils.getName(fileName);
                }

                File uploadedFile = new File(uploadDirectory, fileName);
                if (uploadedFile.createNewFile()) {
                    log.debug("Wrote out " + message.length() + " bytes.");
                    item.write(uploadedFile);
                    saveUploadFileEntry(name, fileName, uploadedFile.getAbsolutePath());
                } else {
                    log.warn("The file already exists in repository: " + uploadedFile.getAbsolutePath());
                    message = "This file already exists in the repository.";
                }
            }

        } catch (Exception e) {
            //                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
            //                        "An error occurred while creating the file : " + e.getMessage());
            log.error("Failed while attempting to upload file: " + e.getMessage(), e);
            message = "Failed to upload file. Error is: " + e.getMessage();
        }

    } else {
        //            resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
        //                            "Request contents type is not supported by the servlet.");
        log.warn("Request contents type is not supported by the service.");
        message = "Upload request contents type is not supported.";
    }
    // Set to expire far in the past.
    resp.setHeader("Expires", "Sat, 6 May 1995 12:00:00 GMT");
    // Set standard HTTP/1.1 no-cache headers.
    resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
    resp.addHeader("Cache-Control", "post-check=0, pre-check=0");
    // Set standard HTTP/1.0 no-cache header.
    resp.setHeader("Pragma", "no-cache");

    resp.setContentType("text/html");
    resp.setContentLength(message.length());
    resp.setStatus(HttpServletResponse.SC_OK);
    resp.getWriter().printf(message);
}

From source file:org.pentaho.platform.dataaccess.datasource.wizard.service.impl.UploadFileDebugServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//from   ww w  .  jav a  2s .co m

        String relativePath = PentahoSystem.getSystemSetting("file-upload-defaults/relative-path",
                String.valueOf(DEFAULT_RELATIVE_UPLOAD_FILE_PATH)); //$NON-NLS-1$
        String maxFileLimit = PentahoSystem.getSystemSetting("file-upload-defaults/max-file-limit", //$NON-NLS-1$
                String.valueOf(MAX_FILE_SIZE));
        String maxFolderLimit = PentahoSystem.getSystemSetting("file-upload-defaults/max-folder-limit", //$NON-NLS-1$
                String.valueOf(MAX_FOLDER_SIZE));
        IPentahoSession session = PentahoSessionHolder.getSession();

        response.setContentType("text/plain"); //$NON-NLS-1$

        FileItem uploadItem = getFileItem(request);
        if (uploadItem == null) {
            String error = Messages.getErrorString("UploadFileDebugServlet.ERROR_0001_NO_FILE_TO_UPLOAD"); //$NON-NLS-1$
            response.getWriter().write(error);
            return;
        }
        if (Long.parseLong(maxFileLimit) < uploadItem.getSize()) {
            String error = Messages.getErrorString("UploadFileDebugServlet.ERROR_0003_FILE_TOO_BIG"); //$NON-NLS-1$
            response.getWriter().write(error);
            return;
        }

        String path = PentahoSystem.getApplicationContext().getSolutionPath(relativePath);
        File pathDir = new File(path);
        // create the path if it doesn't exist yet
        if (!pathDir.exists()) {
            pathDir.mkdirs();
        }

        if (uploadItem.getSize() + getFolderSize(new File(path)) > Long.parseLong(maxFolderLimit)) {
            String error = Messages
                    .getErrorString("UploadFileDebugServlet.ERROR_0004_FOLDER_SIZE_LIMIT_REACHED"); //$NON-NLS-1$
            response.getWriter().write(error);
            return;
        }

        String filename = request.getParameter("file_name"); //$NON-NLS-1$
        if (StringUtils.isEmpty(filename)) {
            filename = UUIDUtil.getUUID().toString();
        }

        String temporary = request.getParameter("mark_temporary"); //$NON-NLS-1$
        boolean isTemporary = false;
        if (temporary != null) {
            isTemporary = Boolean.valueOf(temporary);
        }

        File file;
        if (isTemporary) {
            File tempDir = new File(PentahoSystem.getApplicationContext().getSolutionPath("system/tmp"));
            if (tempDir.exists() == false) {
                tempDir.mkdir();
            }
            file = PentahoSystem.getApplicationContext().createTempFile(session, filename, ".tmp", true); //$NON-NLS-1$
        } else {
            file = new File(path + File.separatorChar + filename);
        }

        FileOutputStream outputStream = new FileOutputStream(file);
        byte[] fileContents = uploadItem.get();
        outputStream.write(fileContents);
        outputStream.flush();
        outputStream.close();

        response.getWriter().write(file.getName());
    } catch (Exception e) {
        String error = Messages.getErrorString("UploadFileDebugServlet.ERROR_0005_UNKNOWN_ERROR", //$NON-NLS-1$
                e.getLocalizedMessage());
        response.getWriter().write(error);
    }
}