Example usage for org.apache.commons.fileupload.disk DiskFileItemFactory DiskFileItemFactory

List of usage examples for org.apache.commons.fileupload.disk DiskFileItemFactory DiskFileItemFactory

Introduction

In this page you can find the example usage for org.apache.commons.fileupload.disk DiskFileItemFactory DiskFileItemFactory.

Prototype

public DiskFileItemFactory() 

Source Link

Document

Constructs an unconfigured instance of this class.

Usage

From source file:com.liferay.faces.bridge.context.map.internal.MultiPartFormDataProcessorImpl.java

@Override
public Map<String, List<UploadedFile>> process(ClientDataRequest clientDataRequest, PortletConfig portletConfig,
        FacesRequestParameterMap facesRequestParameterMap) {

    Map<String, List<UploadedFile>> uploadedFileMap = null;

    PortletSession portletSession = clientDataRequest.getPortletSession();

    String uploadedFilesDir = PortletConfigParam.UploadedFilesDir.getStringValue(portletConfig);

    // Using the portlet sessionId, determine a unique folder path and create the path if it does not exist.
    String sessionId = portletSession.getId();

    // FACES-1452: Non-alpha-numeric characters must be removed order to ensure that the folder will be
    // created properly.
    sessionId = sessionId.replaceAll("[^A-Za-z0-9]", StringPool.BLANK);

    File uploadedFilesPath = new File(uploadedFilesDir, sessionId);

    if (!uploadedFilesPath.exists()) {
        uploadedFilesPath.mkdirs();/*w  w w  .  ja  va  2  s.  co m*/
    }

    // Initialize commons-fileupload with the file upload path.
    DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
    diskFileItemFactory.setRepository(uploadedFilesPath);

    // Initialize commons-fileupload so that uploaded temporary files are not automatically deleted.
    diskFileItemFactory.setFileCleaningTracker(null);

    // Initialize the commons-fileupload size threshold to zero, so that all files will be dumped to disk
    // instead of staying in memory.
    diskFileItemFactory.setSizeThreshold(0);

    // Determine the max file upload size threshold (in bytes).
    long uploadedFileMaxSize = PortletConfigParam.UploadedFileMaxSize.getLongValue(portletConfig);

    // Parse the request parameters and save all uploaded files in a map.
    PortletFileUpload portletFileUpload = new PortletFileUpload(diskFileItemFactory);
    portletFileUpload.setFileSizeMax(uploadedFileMaxSize);
    uploadedFileMap = new HashMap<String, List<UploadedFile>>();

    // FACES-271: Include name+value pairs found in the ActionRequest.
    Set<Map.Entry<String, String[]>> actionRequestParameterSet = clientDataRequest.getParameterMap().entrySet();

    for (Map.Entry<String, String[]> mapEntry : actionRequestParameterSet) {

        String parameterName = mapEntry.getKey();
        String[] parameterValues = mapEntry.getValue();

        if (parameterValues.length > 0) {

            for (String parameterValue : parameterValues) {
                facesRequestParameterMap.addValue(parameterName, parameterValue);
            }
        }
    }

    UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) BridgeFactoryFinder
            .getFactory(UploadedFileFactory.class);

    // Begin parsing the request for file parts:
    try {
        FileItemIterator fileItemIterator = null;

        if (clientDataRequest instanceof ResourceRequest) {
            ResourceRequest resourceRequest = (ResourceRequest) clientDataRequest;
            fileItemIterator = portletFileUpload.getItemIterator(new ActionRequestAdapter(resourceRequest));
        } else {
            ActionRequest actionRequest = (ActionRequest) clientDataRequest;
            fileItemIterator = portletFileUpload.getItemIterator(actionRequest);
        }

        if (fileItemIterator != null) {

            int totalFiles = 0;
            String namespace = facesRequestParameterMap.getNamespace();

            // For each field found in the request:
            while (fileItemIterator.hasNext()) {

                try {
                    totalFiles++;

                    // Get the stream of field data from the request.
                    FileItemStream fieldStream = (FileItemStream) fileItemIterator.next();

                    // Get field name from the field stream.
                    String fieldName = fieldStream.getFieldName();

                    // Get the content-type, and file-name from the field stream.
                    String contentType = fieldStream.getContentType();
                    boolean formField = fieldStream.isFormField();

                    String fileName = null;

                    try {
                        fileName = fieldStream.getName();
                    } catch (InvalidFileNameException e) {
                        fileName = e.getName();
                    }

                    // Copy the stream of file data to a temporary file. NOTE: This is necessary even if the
                    // current field is a simple form-field because the call below to diskFileItem.getString()
                    // will fail otherwise.
                    DiskFileItem diskFileItem = (DiskFileItem) diskFileItemFactory.createItem(fieldName,
                            contentType, formField, fileName);
                    Streams.copy(fieldStream.openStream(), diskFileItem.getOutputStream(), true);

                    // If the current field is a simple form-field, then save the form field value in the map.
                    if (diskFileItem.isFormField()) {
                        String characterEncoding = clientDataRequest.getCharacterEncoding();
                        String requestParameterValue = null;

                        if (characterEncoding == null) {
                            requestParameterValue = diskFileItem.getString();
                        } else {
                            requestParameterValue = diskFileItem.getString(characterEncoding);
                        }

                        facesRequestParameterMap.addValue(fieldName, requestParameterValue);
                    } else {

                        File tempFile = diskFileItem.getStoreLocation();

                        // If the copy was successful, then
                        if (tempFile.exists()) {

                            // Copy the commons-fileupload temporary file to a file in the same temporary
                            // location, but with the filename provided by the user in the upload. This has two
                            // benefits: 1) The temporary file will have a nice meaningful name. 2) By copying
                            // the file, the developer can have access to a semi-permanent file, because the
                            // commmons-fileupload DiskFileItem.finalize() method automatically deletes the
                            // temporary one.
                            String tempFileName = tempFile.getName();
                            String tempFileAbsolutePath = tempFile.getAbsolutePath();

                            String copiedFileName = stripIllegalCharacters(fileName);

                            String copiedFileAbsolutePath = tempFileAbsolutePath.replace(tempFileName,
                                    copiedFileName);
                            File copiedFile = new File(copiedFileAbsolutePath);
                            FileUtils.copyFile(tempFile, copiedFile);

                            // If present, build up a map of headers.
                            Map<String, List<String>> headersMap = new HashMap<String, List<String>>();
                            FileItemHeaders fileItemHeaders = fieldStream.getHeaders();

                            if (fileItemHeaders != null) {
                                Iterator<String> headerNameItr = fileItemHeaders.getHeaderNames();

                                if (headerNameItr != null) {

                                    while (headerNameItr.hasNext()) {
                                        String headerName = headerNameItr.next();
                                        Iterator<String> headerValuesItr = fileItemHeaders
                                                .getHeaders(headerName);
                                        List<String> headerValues = new ArrayList<String>();

                                        if (headerValuesItr != null) {

                                            while (headerValuesItr.hasNext()) {
                                                String headerValue = headerValuesItr.next();
                                                headerValues.add(headerValue);
                                            }
                                        }

                                        headersMap.put(headerName, headerValues);
                                    }
                                }
                            }

                            // Put a valid UploadedFile instance into the map that contains all of the
                            // uploaded file's attributes, along with a successful status.
                            Map<String, Object> attributeMap = new HashMap<String, Object>();
                            String id = Long.toString(((long) hashCode()) + System.currentTimeMillis());
                            String message = null;
                            UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(
                                    copiedFileAbsolutePath, attributeMap, diskFileItem.getCharSet(),
                                    diskFileItem.getContentType(), headersMap, id, message, fileName,
                                    diskFileItem.getSize(), UploadedFile.Status.FILE_SAVED);

                            facesRequestParameterMap.addValue(fieldName, copiedFileAbsolutePath);
                            addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                            logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName,
                                    fileName);
                        } else {

                            if ((fileName != null) && (fileName.trim().length() > 0)) {
                                Exception e = new IOException("Failed to copy the stream of uploaded file=["
                                        + fileName
                                        + "] to a temporary file (possibly a zero-length uploaded file)");
                                UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
                                addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error(e);

                    UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
                    String fieldName = Integer.toString(totalFiles);
                    addUploadedFile(uploadedFileMap, fieldName, uploadedFile);
                }
            }
        }
    }

    // If there was an error in parsing the request for file parts, then put a bogus UploadedFile instance in
    // the map so that the developer can have some idea that something went wrong.
    catch (Exception e) {
        logger.error(e);

        UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e);
        addUploadedFile(uploadedFileMap, "unknown", uploadedFile);
    }

    return uploadedFileMap;
}

From source file:it.swim.servlet.RegistrazioneServlet.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)// www . ja  va 2s .  c o  m
 */
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    List<FileItem> items;
    Blob blob = null;
    String email = new String();
    String password = new String();
    String nome = new String();
    String cognome = new String();

    List<Abilita> abilitaPersonaliRegistrazione = new ArrayList<Abilita>();

    //nel caso ci siano errori e devo tornare alla stessa jsp, preparo subito la lista delle abilita' da rivisualizzare
    // Ottengo abilita dall'insieme generale e le metto nella request
    List<Abilita> abilitaInsiemeGenerale = ricerche.insiemeAbilitaGenerali();
    request.setAttribute("abilita", abilitaInsiemeGenerale);

    try {
        items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

        for (FileItem item : items) {
            if (item.isFormField()) {
                // Process regular form field (input
                // type="text|radio|checkbox|etc", select, etc).
                // ... (do your job here)
                if (item.getFieldName().equals("emailUtente")) {
                    //ottengo il valore del form field
                    email = item.getString();
                }
                if (item.getFieldName().equals("password")) {
                    password = item.getString();
                }
                if (item.getFieldName().equals("nome")) {
                    nome = item.getString();
                }
                if (item.getFieldName().equals("cognome")) {
                    cognome = item.getString();
                }
                if (item.getFieldName().equals("abilita")) {
                    abilitaPersonaliRegistrazione.add(registrazione.getAbilitaByNome(item.getString()));
                }
            } else {
                //non cancellare questi commenti, potranno tornare utili
                // Process form file field (input type="file").
                // String fieldname = item.getFieldName();
                // String filename = item.getName();
                // InputStream filecontent = item.getInputStream();
                try {
                    blob = ConvertitoreFotoInBlob.getBlobFromFileItem(item, LUNGHEZZA, ALTEZZA, DIMMB);
                } catch (FotoException e) {
                    try {
                        if (e.getCausa().equals(FotoException.Causa.FILETROPPOGRANDE)) {
                            blob = ConvertitoreFotoInBlob.getBlobFromDefaultImage();
                            request.setAttribute("erroreFileTroppoGrande",
                                    "Errore, file troppo grande! E' stata impostata la foto di profilo predefinita");
                        } else {
                            if (e.getCausa().equals(FotoException.Causa.NONRICONOSCIUTACOMEFOTO)) {
                                blob = ConvertitoreFotoInBlob.getBlobFromDefaultImage();
                                request.setAttribute("erroreNonFoto",
                                        "Errore, foto non riconosciuta! E' stata impostata la foto di profilo predefinita");
                            }
                        }
                        //in questo caso uploada una foto predefinita
                        blob = ConvertitoreFotoInBlob.getBlobFromDefaultImage();
                        request.setAttribute("erroreFotoSconosciuto",
                                "Errore durante il caricamento della foto! E' stata impostata la foto di profilo predefinita");
                    } catch (FotoException e1) {
                        request.setAttribute("erroreFotoSconosciuto",
                                "Errore durante il caricamento della foto! E' stata impostata la foto di profilo predefinita");
                    }
                }
            }
        }

        log.debug("email: " + email);
        log.debug("password: " + password);
        log.debug("nome: " + nome);
        log.debug("cognome: " + cognome);
        log.debug("Lista abilita passate in registrazione: "
                + Arrays.toString(abilitaPersonaliRegistrazione.toArray()));

        if (blob == null) {
            try {
                blob = ConvertitoreFotoInBlob.getBlobFromDefaultImage();
            } catch (FotoException e) {
                request.setAttribute("erroreFotoPredefinita",
                        "Errore durante il caricamento della foto predefinita. Nessun file caricato!");
            }
        }

    } catch (FileUploadException e) {
        log.error(e.getMessage(), e);
        request.setAttribute("erroreFotoIrreversibile",
                "Errore durante il caricamento della foto! Non e' stata impostata nessuna foto di profilo");
    } catch (SerialException e) {
        log.error(e.getMessage(), e);
        request.setAttribute("erroreFotoIrreversibile",
                "Errore durante il caricamento della foto! Non e' stata impostata nessuna foto di profilo");
    } catch (SQLException e) {
        log.error(e.getMessage(), e);
        request.setAttribute("erroreFotoIrreversibile",
                "Errore durante il caricamento della foto! Non e' stata impostata nessuna foto di profilo");
    }

    Utente utenteRegistrato;
    try {
        utenteRegistrato = registrazione.registrazioneUtente(email, password, nome, cognome, blob,
                abilitaPersonaliRegistrazione);

        log.debug("utenteRegistrato: " + utenteRegistrato);

        if (utenteRegistrato != null) {
            log.debug("Registrazione avvenuta correttamente registrazione");

            request.getSession().setAttribute("utenteCollegato", email);
            request.getSession().setAttribute("nomeUtenteCollegato", utenteRegistrato.getNome());
            request.getSession().setAttribute("cognomeUtenteCollegato", utenteRegistrato.getCognome());
            request.setAttribute("abilita", abilitaPersonaliRegistrazione);
            request.setAttribute("punteggioUtenteCollegato", "Non disponibile");
            getServletConfig().getServletContext().getRequestDispatcher("/jsp/utenti/profilo/profilo.jsp")
                    .forward(request, response);

        } else {
            log.debug("Errore registrazione");
            request.setAttribute("erroreRegistrazione", "Errore durante la registrazione");
            getServletConfig().getServletContext().getRequestDispatcher("/jsp/visitatore/registrazione.jsp")
                    .forward(request, response);
        }
    } catch (HashingException e) {
        log.error(e.getMessage(), e);
        request.setAttribute("erroreHashing", "Errore hashing durante la registrazione");
        getServletConfig().getServletContext().getRequestDispatcher("/jsp/visitatore/registrazione.jsp")
                .forward(request, response);
    } catch (RegistrazioneException e) {
        log.error(e.getMessage(), e);
        if (e.getCausa() == RegistrazioneException.Causa.EMAILGIAUTILIZZATA) {
            request.setAttribute("erroreEmailGiaUsata", "Errore! Indirizzo email gia' in uso");
        }
        if (e.getCausa() == RegistrazioneException.Causa.SINTASSIEMAILNONCORRETTA) {
            request.setAttribute("erroreSintassiEmailNonCorretta", "Errore! Inserisci un'email valida");
        }
        if (e.getCausa() == RegistrazioneException.Causa.ALCUNIPARAMETRINULLIOVUOTI) {
            request.setAttribute("erroreParametriNulliOVuoti",
                    "Errore! Devi completare tutti i campi obbligatori");
        }
        if (e.getCausa() == RegistrazioneException.Causa.ERRORESCONOSCIUTO) {
            request.setAttribute("erroreSconosciutoRegistrazione",
                    "Errore sconosciuto durante la registrazione");
        }
        getServletConfig().getServletContext().getRequestDispatcher("/jsp/visitatore/registrazione.jsp")
                .forward(request, response);
    }
}

From source file:com.ephesoft.gxt.admin.server.ImportDocumentTypeUploadServlet.java

/**
 * This API is used to get uploaded file and create directory for given path in parameter.
 * /*from  ww w . j  a  va 2s. c o  m*/
 * @param filePath {@link String} to create directory.
 * @return {@link ServletFileUpload} uploaded file.
 */
private ServletFileUpload getUploadedFile(final String filePath) {
    final FileItemFactory factory = new DiskFileItemFactory();
    final ServletFileUpload upload = new ServletFileUpload(factory);
    final File exportSerFd = new File(filePath);
    if (!exportSerFd.exists()) {
        exportSerFd.mkdir();
    }
    return upload;
}

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

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

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

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

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

        return;// w ww . j  a  va 2s  . c o  m
    }

    //post - upload

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

    PageService pageService = getPageService();

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

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

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

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

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

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

            files.add(node);

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

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

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

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

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

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

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

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

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

From source file:edu.lternet.pasta.portal.UploadEvaluateServlet.java

/**
 * The doPost method of the servlet. <br>
 * //from w w w.  java  2 s  .com
 * This method is called when a form has its tag value method equals to post.
 * 
 * @param request
 *          the request send by the client to the server
 * @param response
 *          the response send by the server to the client
 * @throws ServletException
 *           if an error occurred
 * @throws IOException
 *           if an error occurred
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession httpSession = request.getSession();

    String uid = (String) httpSession.getAttribute("uid");

    if (uid == null || uid.isEmpty())
        uid = "public";

    String html = null;

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {

        // 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(request);

            // Process the uploaded items
            Iterator iter = items.iterator();

            while (iter.hasNext()) {

                FileItem item = (FileItem) iter.next();

                if (!(item.isFormField())) {

                    File eml = processUploadedFile(item);

                    DataPackageManagerClient dpmClient = new DataPackageManagerClient(uid);
                    String xml = dpmClient.evaluateDataPackage(eml);

                    ReportUtility qrUtility = new ReportUtility(xml);
                    String htmlTable = qrUtility.xmlToHtmlTable(cwd + xslpath);

                    if (htmlTable == null) {
                        String msg = "The uploaded file could not be evaluated.";
                        throw new UserErrorException(msg);
                    } else {
                        html = HTMLHEAD + "<div class=\"qualityreport\">" + htmlTable + "</div>" + HTMLTAIL;
                    }

                }

            }

        } catch (Exception e) {
            handleDataPortalError(logger, e);
        }
    }

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.print(html);
    out.flush();
    out.close();
}

From source file:application.controllers.admin.EmotionList.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    //upload image to browser for add emotions
    //upload image to browser for add emotions
    if (!ServletFileUpload.isMultipartContent(request)) {
        PrintWriter writer = response.getWriter();
        writer.println("Request does not contain upload data");
        writer.flush();//from  w  w w . j  a  va 2 s  . c o  m
        return;
    }

    // configures upload settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    // maximum size that will be stored in memory
    factory.setSizeThreshold(UploadConstant.THRESHOLD_SIZE);
    // Location to save data that is larger than maxMemSize.
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    // maximum file size to be uploaded.
    upload.setFileSizeMax(UploadConstant.MAX_FILE_SIZE);
    upload.setSizeMax(UploadConstant.MAX_REQUEST_SIZE);

    // constructs the directory path to store upload file
    // String uploadPath = Registry.get("Host") +"/emotions-image/"+ UPLOAD_DIRECTORY;
    String uploadPath = Registry.get("imageHost") + "/emotions-image/" + UploadConstant.UPLOAD_DIRECTORY;
    // creates the directory if it does not exist
    File uploadDir = new File(uploadPath);
    if (!uploadDir.exists()) {
        uploadDir.mkdir();
    }

    //list image user upload
    String[] arrLinkImage = null;
    try {
        int indexImage = 0;
        // parses the request's content to extract file data
        List formItems = upload.parseRequest(request);
        arrLinkImage = new String[formItems.size()];
        Iterator iter = formItems.iterator();

        // iterates over form's fields
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            // processes only fields that are not form fields
            if (!item.isFormField()) {
                String fileName = new File(item.getName()).getName();
                String extensionImage = "";
                for (int i = fileName.length() - 1; i >= 0; i--) {
                    if (fileName.charAt(i) == '.') {
                        break;

                    } else {
                        extensionImage = fileName.charAt(i) + extensionImage;
                    }
                }
                String filePath = uploadPath + File.separator + fileName;
                File storeFile = new File(filePath);
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();
                String fieldName = item.getFieldName();

                // saves the file on disk
                item.write(storeFile);
                arrLinkImage[indexImage++] = item.getName();
            }
        }

    } catch (Exception ex) {
        request.setAttribute("message", "There was an error: " + ex.getMessage());
    }

    //   request.setAttribute("arrLinkImage", arrLinkImage);
    //  RequestDispatcher rd = request.getRequestDispatcher("/groupEmotion/emotion/add");
    //   rd.forward(request, response);
    //        String sessionId = request.getAttribute("sessionIdAdmin").toString();
    String sessionId = request.getSession().toString();
    String groupId = request.getParameter("groupId");
    Memcached.set("arrLinkImage-" + sessionId, 3600, arrLinkImage);

    response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
    response.setHeader("Location", Registry.get("Host") + "/groupEmotion/emotion/add?groupId=" + groupId);
    response.setContentType("text/html");

}

From source file:com.ephesoft.dcma.gwt.admin.bm.server.UploadImageFileServlet.java

/**
 * Overridden doPost method./*from   w ww  .j a  v  a2  s.c o m*/
 * 
 * @param request HttpServletRequest
 * @param response HttpServletResponse
 * @throws IOException
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String batchClassId = null;
    String docName = null;
    String fileName = null;
    String isAdvancedTableInfo = null;
    InputStream instream = null;
    OutputStream out = null;
    PrintWriter printWriter = resp.getWriter();
    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);
        List<FileItem> items;
        BatchSchemaService batchSchemaService = this.getSingleBeanOfType(BatchSchemaService.class);
        String uploadPath = null;
        try {
            items = upload.parseRequest(req);
            for (FileItem item : items) {

                // process only file upload - discard other form item types
                if (item.isFormField()) {
                    if (item.getFieldName().equalsIgnoreCase("batchClassID")) {
                        batchClassId = item.getString();
                    } else if (item.getFieldName().equalsIgnoreCase("docName")) {
                        docName = item.getString();
                    } else if (item.getFieldName().equalsIgnoreCase("isAdvancedTableInfo")) {
                        isAdvancedTableInfo = item.getString();
                    }
                } else if (!item.isFormField() && "importFile".equals(item.getFieldName())) {
                    fileName = item.getName();
                    if (fileName != null) {
                        fileName = fileName.substring(fileName.lastIndexOf(File.separator) + 1);
                    }
                    instream = item.getInputStream();
                }
            }
            if (batchClassId == null || docName == null) {
                LOG.error(
                        "Error while loading image... Either batchClassId or doc type is null. Batch Class Id :: "
                                + batchClassId + " Doc Type :: " + docName);
                printWriter.write("Error while loading image... Either batchClassId or doc type is null.");
            } else {
                StringBuilder uploadPathString = uploadPath(batchClassId, docName, isAdvancedTableInfo,
                        batchSchemaService);
                File uploadFolder = new File(uploadPathString.toString());
                if (!uploadFolder.exists()) {
                    try {
                        boolean tempPath = uploadFolder.mkdirs();
                        if (!tempPath) {
                            LOG.error(
                                    "Unable to create the folders in the temp directory specified. Change the path and permissions in dcma-batch.properties");
                            printWriter.write(
                                    "Unable to create the folders in the temp directory specified. Change the path and permissions in dcma-batch.properties");
                            return;
                        }
                    } catch (Exception e) {
                        LOG.error("Unable to create the folders in the temp directory.", e);
                        printWriter
                                .write("Unable to create the folders in the temp directory." + e.getMessage());
                        return;
                    }
                }
                uploadPathString.append(File.separator);
                uploadPathString.append(fileName);
                uploadPath = uploadPathString.toString();
                out = new FileOutputStream(uploadPath);
                byte buf[] = new byte[BatchClassManagementConstants.BUFFER_SIZE];
                int len = instream.read(buf);
                while ((len) > 0) {
                    out.write(buf, 0, len);
                    len = instream.read(buf);
                }
                // convert tiff to png
                ImageProcessService imageProcessService = this.getSingleBeanOfType(ImageProcessService.class);
                imageProcessService.generatePNGForImage(new File(uploadPath));
                LOG.info("Png file created successfully for file: " + uploadPath);
            }
        } catch (FileUploadException e) {
            LOG.error("Unable to read the form contents." + e, e);
            printWriter.write("Unable to read the form contents.Please try again.");
        } catch (DCMAException e) {
            LOG.error("Unable to generate PNG." + e, e);
            printWriter.write("Unable to generate PNG.Please try again.");
        } finally {
            if (out != null) {
                out.close();
            }
            if (instream != null) {
                instream.close();
            }
        }
        printWriter.write("file_seperator:" + File.separator);
        printWriter.write("|");
    }
}

From source file:com.ephesoft.dcma.gwt.uploadbatch.server.UploadBatchImageServlet.java

private void uploadFile(HttpServletRequest req, HttpServletResponse resp, BatchSchemaService batchSchemaService,
        String currentBatchUploadFolderName) throws IOException {
    PrintWriter printWriter = resp.getWriter();
    File tempFile = null;/*from w  w  w  . j a  va  2  s.c  o m*/
    InputStream instream = null;
    OutputStream out = null;
    String uploadBatchFolderPath = batchSchemaService.getUploadBatchFolder();
    String uploadFileName = "";
    if (ServletFileUpload.isMultipartContent(req)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        uploadFileName = "";
        String uploadFilePath = "";
        List<FileItem> items;
        try {
            items = upload.parseRequest(req);

            for (FileItem item : items) {
                if (!item.isFormField()) { // && "uploadFile".equals(item.getFieldName())) {
                    uploadFileName = item.getName();
                    if (uploadFileName != null) {
                        uploadFileName = uploadFileName
                                .substring(uploadFileName.lastIndexOf(File.separator) + 1);
                    }
                    uploadFilePath = uploadBatchFolderPath + File.separator + currentBatchUploadFolderName
                            + File.separator + uploadFileName;

                    try {
                        instream = item.getInputStream();
                        tempFile = new File(uploadFilePath);

                        out = new FileOutputStream(tempFile);
                        byte buf[] = new byte[1024];
                        int len = instream.read(buf);
                        while (len > 0) {
                            out.write(buf, 0, len);
                            len = instream.read(buf);
                        }
                    } catch (FileNotFoundException e) {
                        LOG.error("Unable to create the upload folder." + e, e);
                        printWriter.write("Unable to create the upload folder.Please try again.");

                    } catch (IOException e) {
                        LOG.error("Unable to read the file." + e, e);
                        printWriter.write("Unable to read the file.Please try again.");
                    } finally {
                        if (out != null) {
                            out.close();
                        }
                        if (instream != null) {
                            instream.close();
                        }
                    }
                }
            }
        } catch (FileUploadException e) {
            LOG.error("Unable to read the form contents." + e, e);
            printWriter.write("Unable to read the form contents.Please try again.");
        }

    } else {
        LOG.error("Request contents type is not supported.");
        printWriter.write("Request contents type is not supported.");
    }
    printWriter.write("currentBatchUploadFolderName:" + currentBatchUploadFolderName);
    printWriter.append("|");

    printWriter.append("fileName:").append(uploadFileName);
    printWriter.append("|");

    printWriter.flush();
}

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

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

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

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

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

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

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

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

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