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.idr.servlets.UploadServlet.java

/**
 * Uploading the file to the sever and complete the conversion
 * @param request//from w  w w .  j av a  2  s  . com
 * @param response 
 */
private void doFileUpload(HttpServletRequest request, HttpServletResponse response) {

    //        System.out.println("Doing upload"+System.currentTimeMillis());
    HttpSession session = request.getSession();

    session.setAttribute("href", null);
    session.setAttribute("FILE_UPLOAD_STATS", null);
    session.setAttribute("pageCount", 0);
    session.setAttribute("pageReached", 0);
    session.setAttribute("isUploading", "true");
    session.setAttribute("isConverting", "false");
    session.setAttribute("convertType", "html");
    session.setAttribute("isZipping", "false");
    con = new Converter();
    byte[] fileBytes = null;

    String sessionId = session.getId();
    String userFileName = "";
    HashMap<String, String> paramMap = new HashMap<String, String>();
    int conType = Converter.getConversionType(request.getRequestURI());

    int startPageNumber = 1;
    int pageCount = 0;

    try {

        if (ServletFileUpload.isMultipartContent(request)) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            UploadListener listener = new UploadListener();//listens file uploads                  
            upload.setProgressListener(listener);
            session.setAttribute("FILE_UPLOAD_STATS", listener);
            List<FileItem> fields = upload.parseRequest(request);
            Iterator<FileItem> it = fields.iterator();
            FileItem fileItem = null;
            if (!it.hasNext()) {
                return;//("No fields found");
            }
            while (it.hasNext()) {
                FileItem field = it.next();
                if (field.isFormField()) {
                    String fieldName = field.getFieldName();
                    Flag.updateParameterMap(fieldName, field.getString(), paramMap);
                    field.delete();
                } else {
                    fileItem = field;
                }
            }
            //Flags whether the file is a .zip or a .pdf
            if (fileItem.getName().contains(".pdf")) {
                isPDF = true;
                isZip = false;
            } else if (fileItem.getName().contains(".zip")) {
                isZip = true;
                isPDF = false;
            }
            //removes the last 4 chars and replaces odd chars with underscore
            userFileName = fileItem.getName().substring(0, fileItem.getName().length() - 4)
                    .replaceAll("[^a-zA-Z0-9]", "_");
            fileBytes = fileItem.get();
            fileItem.delete();
        }

        // Delete existing editor files if any exist. 
        if (isEditorLinkOutput) {
            File editorFolder = new File(Converter.EDITORPATH + "/" + sessionId + "/");
            if (editorFolder.exists()) {
                FileUtils.deleteDirectory(editorFolder);
            }
        }
        con.initializeConversion(sessionId, userFileName, fileBytes, isZip);
        PdfDecoderServer decoder = new PdfDecoderServer(false);
        decoder.openPdfFile(con.getUserPdfFilePath());
        pageCount = decoder.getPageCount();
        //Check whether or not the PDF contains forms
        if (decoder.isForm()) {
            session.setAttribute("isForm", "true"); //set an attrib for extraction.jps to use
            response.getWriter().println("<div id='isForm'></div>");
        } else if (!decoder.isForm()) {
            session.setAttribute("isForm", "false"); //set an attrib for extraction.jps to use
        }
        //Check whther or not the PDF is XFA
        if (decoder.getFormRenderer().isXFA()) {
            session.setAttribute("isXFA", "true");
            //                response.getWriter().println("<div id='isXFA'></div>");
        } else if (!decoder.getFormRenderer().isXFA()) {
            session.setAttribute("isXFA", "false");
        }
        decoder.closePdfFile(); //closes file

        if (paramMap.containsKey("org.jpedal.pdf2html.realPageRange")) {
            String tokensCSV = (String) paramMap.get("org.jpedal.pdf2html.realPageRange");
            PageRanges range = new PageRanges(tokensCSV);
            ArrayList<Integer> rangeList = new ArrayList<Integer>();
            for (int z = 0; z < pageCount; z++) {
                if (range.contains(z)) {
                    rangeList.add(z);
                }
            }
            int userPageCount = rangeList.size();
            if (rangeList.size() > 0) {
                session.setAttribute("pageCount", userPageCount);
            } else {
                throw new Exception("invalid Page Range");
            }
        } else {
            session.setAttribute("pageCount", pageCount);
        }

        session.setAttribute("isUploading", "false");
        session.setAttribute("isConverting", "true");

        String scales = paramMap.get("org.jpedal.pdf2html.scaling");
        String[] scaleArr = null;
        String userOutput = con.getUserFileDirName();
        if (scales != null && scales.contains(",")) {
            scaleArr = scales.split(",");
        }

        String reference = UploadServlet.getConvertedFileHref(sessionId, userFileName, conType, pageCount,
                startPageNumber, paramMap, scaleArr, isZip) + "<br/><br/>";

        if (isZipLinkOutput) {
            reference = reference + con.getZipFileHref(userOutput, scaleArr);
        }

        if (isEditorLinkOutput && conType != Converter.PDF2ANDROID && conType != Converter.PDF2IMAGE) {
            reference = reference + "<br/><br/>" + con.getEditorHref(userOutput, scaleArr); // editor link
        }
        String typeString = Converter.getConversionTypeAsString(conType);

        converterThread(userFileName, scaleArr, fileBytes, typeString, paramMap, session, pageCount, reference);

    } catch (Exception ex) {
        session.setAttribute("href", "<end></end><div class='errorMsg'>Error: " + ex.getMessage() + "</div>");
        Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
        cancelUpload(request, response);
    }
}

From source file:fr.paris.lutece.plugins.form.business.EntryTypeFile.java

/**
 * save in the list of response the response associate to the entry in the form submit
 * @param request HttpRequest//from  w  w  w.j  a  v a  2 s  . co  m
 * @param listResponse the list of response associate to the entry in the form submit
 * @param locale the locale
 * @return a Form error object if there is an error in the response
 */
public FormError getResponseData(HttpServletRequest request, List<Response> listResponse, Locale locale) {
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    FileItem fileSource = multipartRequest.getFile(FormUtils.EMPTY_STRING + this.getIdEntry());
    String strFilename = FileUploadService.getFileNameOnly(fileSource);
    List<RegularExpression> listRegularExpression = this.getFields().get(0).getRegularExpressionList();

    Response response = new Response();
    response.setEntry(this);

    if (this.isMandatory()) {
        if ((strFilename == null) || (strFilename.equals(EMPTY_STRING))) {
            FormError formError = new FormError();
            formError.setMandatoryError(true);
            formError.setTitleQuestion(this.getTitle());

            return formError;
        }
    }

    String strMimeType = fileSource.getContentType();

    if ((strFilename != null) && (!strFilename.equals(EMPTY_STRING)) && (listRegularExpression != null)
            && (listRegularExpression.size() != 0) && RegularExpressionService.getInstance().isAvailable()) {
        for (RegularExpression regularExpression : listRegularExpression) {
            if (!RegularExpressionService.getInstance().isMatches(strMimeType, regularExpression)) {
                FormError formError = new FormError();
                formError.setMandatoryError(false);
                formError.setTitleQuestion(this.getTitle());
                formError.setErrorMessage(regularExpression.getErrorMessage());

                return formError;
            }
        }
    }

    byte[] byValueEntry = fileSource.get();

    response.setValueResponse(byValueEntry);
    response.setFileName(strFilename);
    response.setFileExtension(FilenameUtils.getExtension(strFilename));
    listResponse.add(response);

    return null;
}

From source file:it.eng.spagobi.mapcatalogue.service.DetailMapModule.java

private GeoMap recoverMapDetails(SourceBean serviceRequest)
        throws EMFUserError, SourceBeanException, IOException {
    GeoMap map = new GeoMap();

    String idStr = (String) serviceRequest.getAttribute("ID");
    Integer id = new Integer(idStr);
    String description = (String) serviceRequest.getAttribute("DESCR");
    String name = (String) serviceRequest.getAttribute("NAME");
    String format = (String) serviceRequest.getAttribute("FORMAT");
    Integer binId = new Integer((String) serviceRequest.getAttribute("BIN_ID"));

    map.setMapId(id.intValue());//from   ww  w .  j a va2s .  co m
    map.setName(name);
    map.setDescr(description);
    map.setFormat(format);
    map.setBinId(binId);

    //gets the file eventually uploaded and sets the content variable
    FileItem uploaded = (FileItem) serviceRequest.getAttribute("UPLOADED_FILE");
    String fileName = null;
    if (uploaded != null) {
        fileName = GeneralUtilities.getRelativeFileNames(uploaded.getName());
        if (uploaded.getSize() == 0
                && ((String) serviceRequest.getAttribute("MESSAGEDET")).equals("DETAIL_INS")) {
            EMFValidationError error = new EMFValidationError(EMFErrorSeverity.ERROR, "uploadFile", "201");
            getErrorHandler().addError(error);
            return map;
        }
        int maxSize = GeneralUtilities.getTemplateMaxSize();
        if (uploaded.getSize() > maxSize
                && ((String) serviceRequest.getAttribute("MESSAGEDET")).equals("DETAIL_INS")) {
            EMFValidationError error = new EMFValidationError(EMFErrorSeverity.ERROR, "uploadFile", "202");
            getErrorHandler().addError(error);
            return map;
        }
        if (uploaded.getSize() > 0) {
            try {
                content = uploaded.get();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    return map;
}

From source file:com.bibisco.servlet.BibiscoServlet.java

public void importProjectArchiveFile(HttpServletRequest pRequest, HttpServletResponse pResponse)
        throws ServletException, IOException {

    mLog.debug("Start importProjectArchiveFile(HttpServletRequest, HttpServletResponse)");

    byte[] lBytes = null;

    // get file item
    FileItem lFileItem = (FileItem) pRequest.getAttribute("file-document_file");
    if (lFileItem.getName() == null || lFileItem.getName().length() == 0) {
        lFileItem = null;/*  w  w  w  . ja v a 2  s .  com*/
    } else {
        lBytes = lFileItem.get();
        mLog.debug("FileItem " + lFileItem.getName());
    }

    ImportProjectArchiveDTO lImportProjectArchiveDTO = ProjectManager
            .importProjectArchiveFile(lFileItem.getName(), lBytes);

    pRequest.setAttribute("importProjectArchive", lImportProjectArchiveDTO);
    pRequest.getRequestDispatcher(CLOSE_IMPORT_PROJECT).forward(pRequest, pResponse);

    mLog.debug("End importProjectArchiveFile(HttpServletRequest, HttpServletResponse)");
}

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

/**
 * Get the request data and if there is no error insert the data in the icon object specified in parameter.
 * return null if there is no error or else return the error page url
 * @param  request the request/*  w ww.  ja  va  2s  . co  m*/
 * @param icon the Icon Object
 * @return null if there is no error or else return the error page url
 */
private String getIconData(HttpServletRequest request, Icon icon) {
    String strError = WorkflowUtils.EMPTY_STRING;
    String strName = request.getParameter(PARAMETER_NAME);
    String strWidth = request.getParameter(PARAMETER_WIDTH);
    String strHeight = request.getParameter(PARAMETER_HEIGHT);

    int nWidth = WorkflowUtils.convertStringToInt(strWidth);
    int nHeight = WorkflowUtils.convertStringToInt(strHeight);

    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    FileItem fileItem = multipartRequest.getFile(PARAMETER_ID_FILE);

    if ((strName == null) || strName.trim().equals(EMPTY_STRING)) {
        strError = FIELD_NAME;
    } else if ((icon.getValue() == null) && ((fileItem == null)
            || ((fileItem.getName() == null) && WorkflowUtils.EMPTY_STRING.equals(fileItem.getName())))) {
        strError = FIELD_FILE;
    }

    //Mandatory fields
    if (!strError.equals(EMPTY_STRING)) {
        Object[] tabRequiredFields = { I18nService.getLocalizedString(strError, getLocale()) };

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

    if ((strWidth != null) && (!strWidth.trim().equals(WorkflowUtils.EMPTY_STRING)) && (nWidth == -1)) {
        strError = FIELD_WIDTH;
    } else if ((strHeight != null) && (!strHeight.trim().equals(WorkflowUtils.EMPTY_STRING))
            && (nHeight == -1)) {
        strError = FIELD_HEIGHT;
    }

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

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

    icon.setName(strName);

    if ((fileItem != null) && (fileItem.getName() != null)
            && !WorkflowUtils.EMPTY_STRING.equals(fileItem.getName())) {
        icon.setValue(fileItem.get());
        icon.setMimeType(fileItem.getContentType());
    } else {
        icon.setValue(null);
    }

    icon.setWidth(nWidth);
    icon.setHeight(nHeight);

    return null;
}

From source file:fr.paris.lutece.plugins.directory.service.upload.DirectoryAsynchronousUploadHandler.java

/**
 * Performs an upload action.//  w w  w.j a  v  a2  s . c  om
 *
 * @param request the HTTP request
 * @param strUploadAction the name of the upload action
 * @param map the map of <idEntry, RecordFields>
 * @param record the record
 * @param plugin the plugin
 * @throws DirectoryErrorException exception if there is an error
 */
public void doUploadAction(HttpServletRequest request, String strUploadAction,
        Map<String, List<RecordField>> map, Record record, Plugin plugin) throws DirectoryErrorException {
    // Get the name of the upload field
    String strIdEntry = (strUploadAction.startsWith(UPLOAD_SUBMIT_PREFIX)
            ? strUploadAction.substring(UPLOAD_SUBMIT_PREFIX.length())
            : strUploadAction.substring(UPLOAD_DELETE_PREFIX.length()));

    String strFieldName = buildFieldName(strIdEntry);

    if (strUploadAction.startsWith(UPLOAD_SUBMIT_PREFIX)) {
        // A file was submitted
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

        FileItem fileItem = multipartRequest.getFile(strFieldName);

        if (fileItem != null) {
            // Check if the file can be uploaded first
            List<FileItem> listFileItemsToUpload = new ArrayList<FileItem>();
            listFileItemsToUpload.add(fileItem);

            HttpSession session = request.getSession();
            // The following method call throws a DirectoryErrorException if the file cannot be uploaded
            canUploadFiles(strFieldName, getFileItems(strIdEntry, session.getId()), listFileItemsToUpload,
                    request.getLocale());

            // Add the file to the map of <idEntry, RecordFields>
            IEntry entry = EntryHome.findByPrimaryKey(DirectoryUtils.convertStringToInt(strIdEntry), plugin);

            if (entry != null) {
                RecordField recordField = new RecordField();
                recordField.setRecord(record);
                recordField.setEntry(entry);

                String strFilename = FileUploadService.getFileNameOnly(fileItem);

                if ((fileItem.get() != null) && (fileItem.getSize() < Integer.MAX_VALUE)) {
                    if (entry instanceof EntryTypeDownloadUrl) {
                        recordField.setFileName(strFilename);
                        recordField.setFileExtension(FileSystemUtil.getMIMEType(strFilename));
                    } else {
                        PhysicalFile physicalFile = new PhysicalFile();
                        physicalFile.setValue(fileItem.get());

                        File file = new File();
                        file.setPhysicalFile(physicalFile);
                        file.setTitle(strFilename);
                        file.setSize((int) fileItem.getSize());
                        file.setMimeType(FileSystemUtil.getMIMEType(strFilename));

                        recordField.setFile(file);
                    }
                }

                List<RecordField> listRecordFields = map.get(strIdEntry);

                if (listRecordFields == null) {
                    listRecordFields = new ArrayList<RecordField>();
                }

                listRecordFields.add(recordField);
                map.put(strIdEntry, listRecordFields);
            }

            // Add to the asynchronous uploaded files map
            addFileItemToUploadedFile(fileItem, strIdEntry, request.getSession());
        }
    } else if (strUploadAction.startsWith(UPLOAD_DELETE_PREFIX)) {
        HttpSession session = request.getSession(false);

        if (session != null) {
            // Some previously uploaded files were deleted
            // Build the prefix of the associated checkboxes
            String strPrefix = UPLOAD_CHECKBOX_PREFIX + strIdEntry;

            // Look for the checkboxes in the request
            Enumeration<String> enumParamNames = request.getParameterNames();
            List<Integer> listIndexes = new ArrayList<Integer>();

            while (enumParamNames.hasMoreElements()) {
                String strParamName = enumParamNames.nextElement();

                if (strParamName.startsWith(strPrefix)) {
                    // Get the index from the name of the checkbox
                    listIndexes.add(Integer.parseInt(strParamName.substring(strPrefix.length())));
                }
            }

            Collections.sort(listIndexes);
            Collections.reverse(listIndexes);

            for (int nIndex : listIndexes) {
                // Remove from the map of <idEntry, RecordField>
                List<RecordField> listRecordFields = map.get(strIdEntry);

                if (listRecordFields != null) {
                    listRecordFields.remove(nIndex);
                }

                // Remove from the asynchronous uploaded files map
                removeFileItem(strIdEntry, session.getId(), nIndex);
            }
        }
    }
}

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

protected void processUploadParameters(Map uploads, HttpServletRequest request) throws XFormsException {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("updating " + uploads.keySet().size() + " uploads(s)");
    }/*from   w  ww.  ja  v a2  s.c  o m*/

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

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

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

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

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

                    // todo: externalize file handling and uri generation

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

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

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

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

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

From source file:com.cognitivabrasil.repositorio.web.FileController.java

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
@ResponseBody//ww w .  j ava  2  s.  com
public String upload(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, org.apache.commons.fileupload.FileUploadException {
    if (file == null) {
        file = new Files();
        file.setSizeInBytes(0L);
    }

    Integer docId = null;
    String docPath = null;
    String responseString = RESP_SUCCESS;
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {
        try {
            ServletFileUpload x = new ServletFileUpload(new DiskFileItemFactory());
            List<FileItem> items = x.parseRequest(request);

            for (FileItem item : items) {
                InputStream input = item.getInputStream();

                // Handle a form field.
                if (item.isFormField()) {
                    String attribute = item.getFieldName();
                    String value = Streams.asString(input);

                    switch (attribute) {
                    case "chunks":
                        this.chunks = Integer.parseInt(value);
                        break;
                    case "chunk":
                        this.chunk = Integer.parseInt(value);
                        break;
                    case "filename":
                        file.setName(value);
                        break;
                    case "docId":
                        if (value.isEmpty()) {
                            throw new org.apache.commons.fileupload.FileUploadException(
                                    "No foi informado o id do documento.");
                        }
                        docId = Integer.parseInt(value);
                        docPath = Config.FILE_PATH + "/" + docId;
                        File documentPath = new File(docPath);
                        // cria o diretorio
                        documentPath.mkdirs();

                        break;
                    default:
                        break;
                    }

                } // Handle a multi-part MIME encoded file.
                else {
                    try {

                        File uploadFile = new File(docPath, item.getName());
                        BufferedOutputStream bufferedOutput;
                        bufferedOutput = new BufferedOutputStream(new FileOutputStream(uploadFile, true));

                        byte[] data = item.get();
                        bufferedOutput.write(data);
                        bufferedOutput.close();
                    } catch (Exception e) {
                        LOG.error("Erro ao salvar o arquivo.", e);
                        file = null;
                        throw e;
                    } finally {
                        if (input != null) {
                            try {
                                input.close();
                            } catch (IOException e) {
                                LOG.error("Erro ao fechar o ImputStream", e);
                            }
                        }

                        file.setName(item.getName());
                        file.setContentType(item.getContentType());
                        file.setPartialSize(item.getSize());
                    }
                }
            }

            if ((this.chunk == this.chunks - 1) || this.chunks == 0) {
                file.setLocation(docPath + "/" + file.getName());
                if (docId != null) {
                    file.setDocument(documentsService.get(docId));
                }
                fileService.save(file);
                file = null;
            }
        } catch (org.apache.commons.fileupload.FileUploadException | IOException | NumberFormatException e) {
            responseString = RESP_ERROR;
            LOG.error("Erro ao salvar o arquivo", e);
            file = null;
            throw e;
        }
    } // Not a multi-part MIME request.
    else {
        responseString = RESP_ERROR;
    }

    response.setContentType("application/json");
    byte[] responseBytes = responseString.getBytes();
    response.setContentLength(responseBytes.length);
    ServletOutputStream output = response.getOutputStream();
    output.write(responseBytes);
    output.flush();
    return responseString;
}

From source file:fr.paris.lutece.plugins.upload.web.UploadJspBean.java

/**
 * Process file upload/*from w  w w  . j a v  a2s .  co  m*/
 *
 * @param request Http request
 * @return Html form
 */
public String doCreateFile(HttpServletRequest request) {
    String strDirectoryIndex = null;

    try {
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        FileItem item = multiRequest.getFile(PARAMETER_FILE_NAME);

        // The index and value of the directory combo in the form
        strDirectoryIndex = multiRequest.getParameter(PARAMETER_DIRECTORY);

        String strRelativeDirectory = getDirectory(strDirectoryIndex);

        // The absolute path of the target directory
        String strDestDirectory = AppPathService.getWebAppPath() + strRelativeDirectory;

        // List the files in the target directory
        File[] existingFiles = (new File(strDestDirectory)).listFiles();

        // Is the 'unzip' checkbox checked?
        boolean bUnzip = (multiRequest.getParameter(PARAMETER_UNZIP) != null);

        if (item != null && !item.getName().equals(StringUtils.EMPTY)) {
            if (!bUnzip) // copy the file
            {
                AppLogService.debug("copying the file");

                // Getting downloadFile's name
                String strNameFile = FileUploadService.getFileNameOnly(item);

                // Clean name
                String strClearName = UploadUtil.cleanFileName(strNameFile);

                // Checking duplicate
                if (duplicate(strClearName, existingFiles)) {
                    return AdminMessageService.getMessageUrl(request, MESSAGE_FILE_EXISTS,
                            AdminMessage.TYPE_STOP);
                }

                // Move the file to the target directory
                File destFile = new File(strDestDirectory, strClearName);

                FileOutputStream fos = new FileOutputStream(destFile);
                fos.flush();
                fos.write(item.get());
                fos.close();
            } else // unzip the file
            {
                AppLogService.debug("unzipping the file");

                ZipFile zipFile;

                try {
                    // Create a temporary file with result of getTime() as unique file name
                    File tempFile = File.createTempFile(Long.toString((new Date()).getTime()), ".zip");
                    // Delete temp file when program exits.
                    tempFile.deleteOnExit();

                    FileOutputStream fos = new FileOutputStream(tempFile);
                    fos.flush();
                    fos.write(item.get());
                    fos.close();
                    zipFile = new ZipFile(tempFile);
                } catch (ZipException ze) {
                    AppLogService.error("Error opening zip file", ze);

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

                // Each zipped file is indentified by a zip entry :
                Enumeration zipEntries = zipFile.entries();

                while (zipEntries.hasMoreElements()) {
                    ZipEntry zipEntry = (ZipEntry) zipEntries.nextElement();

                    // Clean the name :
                    String strZippedName = zipEntry.getName();
                    String strClearName = UploadUtil.cleanFilePath(strZippedName);

                    if (strZippedName.equals(strClearName)) {
                        // The unzipped file :
                        File destFile = new File(strDestDirectory, strClearName);

                        // Create the parent directory structure if needed :
                        destFile.getParentFile().mkdirs();

                        if (!zipEntry.isDirectory()) // don't unzip directories
                        {
                            AppLogService.debug("unzipping " + strZippedName + " to " + destFile.getName());

                            // InputStream from zipped data
                            InputStream inZipStream = zipFile.getInputStream(zipEntry);

                            // OutputStream to the destination file
                            OutputStream outDestStream = new FileOutputStream(destFile);

                            // Helper method to copy data
                            copyStream(inZipStream, outDestStream);

                            inZipStream.close();
                            outDestStream.close();
                        } else {
                            AppLogService.debug("skipping directory " + strZippedName);
                        }
                    } else {
                        AppLogService.debug("skipping accented file " + strZippedName);
                    }
                }
            }
        } else {
            return AdminMessageService.getMessageUrl(request, Messages.MANDATORY_FIELDS,
                    AdminMessage.TYPE_STOP);
        }
    } catch (IOException e) {
        AppLogService.error(e.getMessage(), e);
    }

    // Returns upload management page
    UrlItem url = new UrlItem(getHomeUrl(request));

    if (strDirectoryIndex != null) {
        url.addParameter(PARAMETER_DIRECTORY, strDirectoryIndex);
    }

    return url.getUrl();
}

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

/**
 * Sends the mail with the form data to the specified recipients.<p>
 * /*  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
 */
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 = (Map<String, FileItem>) getRequest().getSession()
                    .getAttribute(ATTRIBUTE_FILEITEMS);
            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;
}