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

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

Introduction

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

Prototype

InputStream getInputStream() throws IOException;

Source Link

Document

Returns an java.io.InputStream InputStream that can be used to retrieve the contents of the file.

Usage

From source file:com.dotmarketing.portlets.cmsmaintenance.ajax.IndexAjaxAction.java

public void restoreIndex(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, DotDataException {
    try {//from w w  w. jav  a2s .  c  o m
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = (List<FileItem>) upload.parseRequest(request);

        String indexToRestore = null;
        boolean clearBeforeRestore = false;
        String aliasToRestore = null;
        File ufile = null;
        boolean isFlash = false;
        for (FileItem it : items) {
            if (it.getFieldName().equalsIgnoreCase("indexToRestore")) {
                indexToRestore = it.getString().trim();
            } else if (it.getFieldName().equalsIgnoreCase("aliasToRestore")) {
                aliasToRestore = it.getString().trim();
            } else if (it.getFieldName().equalsIgnoreCase("uploadedfiles[]")
                    || it.getFieldName().equals("uploadedfile")
                    || it.getFieldName().equalsIgnoreCase("uploadedfileFlash")) {
                isFlash = it.getFieldName().equalsIgnoreCase("uploadedfileFlash");
                ufile = File.createTempFile("indexToRestore", "idx");
                InputStream in = it.getInputStream();
                FileOutputStream out = new FileOutputStream(ufile);
                IOUtils.copyLarge(in, out);
                IOUtils.closeQuietly(out);
                IOUtils.closeQuietly(in);
            } else if (it.getFieldName().equalsIgnoreCase("clearBeforeRestore")) {
                clearBeforeRestore = true;
            }
        }

        if (LicenseUtil.getLevel() >= 200) {
            if (UtilMethods.isSet(aliasToRestore)) {
                String indexName = APILocator.getESIndexAPI()
                        .getAliasToIndexMap(APILocator.getSiteSearchAPI().listIndices()).get(aliasToRestore);
                if (UtilMethods.isSet(indexName))
                    indexToRestore = indexName;
            } else if (!UtilMethods.isSet(indexToRestore)) {
                indexToRestore = APILocator.getIndiciesAPI().loadIndicies().site_search;
            }
        }

        if (ufile != null) {
            final boolean clear = clearBeforeRestore;
            final String index = indexToRestore;
            final File file = ufile;
            new Thread() {
                public void run() {
                    try {
                        if (clear)
                            APILocator.getESIndexAPI().clearIndex(index);
                        APILocator.getESIndexAPI().restoreIndex(file, index);
                        Logger.info(this, "finished restoring index " + index);
                    } catch (Exception ex) {
                        Logger.error(IndexAjaxAction.this, "Error restoring", ex);
                    }
                }
            }.start();

        }

        PrintWriter out = response.getWriter();
        if (isFlash) {
            out.println("response=ok");
        } else {
            response.setContentType("application/json");
            out.println("{\"response\":1}");
        }

    } catch (FileUploadException fue) {
        Logger.error(this, "Error uploading file", fue);
        throw new IOException(fue);
    }
}

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

@Override
@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");
    boolean persist = WebUtils.getBoolean(request, "persist");
    String userId = request.getRemoteUser();
    Session dbSession = null;/*from  ww w .j av a 2  s .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);
            Language lang = new Language();
            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("lg_id")) {
                        lang.setId(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("lg_name")) {
                        lang.setName(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("persist")) {
                        persist = true;
                    }
                } else {
                    is = item.getInputStream();
                    data = IOUtils.toByteArray(is);
                    lang.setImageMime(MimeTypeConfig.mimeTypes.getContentType(item.getName()));
                    is.close();
                }
            }

            if (action.equals("create")) {
                lang.setImageContent(SecureStore.b64Encode(data));
                LanguageDAO.create(lang);

                // Activity log
                UserActivity.log(request.getRemoteUser(), "ADMIN_LANGUAGE_CREATE", lang.getId(), null,
                        lang.toString());
            } else if (action.equals("edit")) {
                lang.setImageContent(SecureStore.b64Encode(data));
                LanguageDAO.update(lang);

                // Activity log
                UserActivity.log(request.getRemoteUser(), "ADMIN_LANGUAGE_EDIT", lang.getId(), null,
                        lang.toString());
            } else if (action.equals("delete")) {
                LanguageDAO.delete(lang.getId());

                // Activity log
                UserActivity.log(request.getRemoteUser(), "ADMIN_LANGUAGE_DELETE", lang.getId(), null, null);
            } else if (action.equals("import")) {
                dbSession = HibernateUtil.getSessionFactory().openSession();
                importLanguage(userId, request, response, data, dbSession);

                // Activity log
                UserActivity.log(request.getRemoteUser(), "ADMIN_LANGUAGE_IMPORT", null, null, null);
            }
        } else if (action.equals("translate")) {
            translate(userId, request, response);
        } else if (action.equals("addTranslation")) {
            addTranslation(userId, request, response);
        }

        if (!action.equals("addTranslation") && (action.equals("") || action.equals("import") || persist)) {
            list(userId, request, response);
        }
    } catch (FileUploadException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (DatabaseException 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);
    }
}

From source file:com.silverpeas.socialnetwork.myProfil.servlets.MyProfilRequestRouter.java

/**
 * method to change profile Photo//from   w w w  . ja v a 2s. c  om
 *
 * @param request
 * @param nameAvatar
 * @return String
 * @throws UtilException
 */
protected String saveAvatar(HttpRequest request, String nameAvatar) throws UtilException {
    List<FileItem> parameters = request.getFileItems();
    String removeImageFile = FileUploadUtil.getParameter(parameters, "removeImageFile");
    FileItem file = FileUploadUtil.getFile(parameters, "WAIMGVAR0");
    ImageProfil img = new ImageProfil(nameAvatar);
    if (file != null && StringUtil.isDefined(file.getName())) {// Create or Update
        // extension
        String extension = FileRepositoryManager.getFileExtension(file.getName());
        if (extension != null && extension.equalsIgnoreCase("jpeg")) {
            extension = "jpg";
        }

        if (!"gif".equalsIgnoreCase(extension) && !"jpg".equalsIgnoreCase(extension)
                && !"png".equalsIgnoreCase(extension)) {
            throw new UtilException("MyProfilRequestRouter.saveAvatar()", SilverpeasRuntimeException.ERROR, "",
                    "Bad extension, .gif or .jpg or .png expected.");
        }
        try {
            img.saveImage(file.getInputStream());
        } catch (IOException e) {
            throw new UtilException("MyProfilRequestRouter.saveAvatar()", SilverpeasRuntimeException.ERROR, "",
                    "Problem while saving image.");
        }
    } else if ("yes".equals(removeImageFile)) {// Remove
        img.removeImage();
    }
    return nameAvatar;
}

From source file:com.netfinworks.rest.convert.MultiPartFormDataParamConvert.java

public <T> void processUploadedFile(FileItem item, T pojo) {
    try {/*www  . j av a 2s  .co  m*/
        String name = item.getFieldName();
        if (name == null || Magic.EmtpyString.equals(name)) {
            return;
        }
        Class<?> cls = getPropertyClass(pojo.getClass(), name);
        if (cls == null) {
            return;
        }
        if (cls.equals(String.class)) {
            String value = item.getString(encoding);
            IParamConvert paramConvert = classParamConvertRegistry.get(cls.getName());
            Object oldValue = getPropertyValue(pojo, pojo.getClass(), name);
            Object convertedValue = ConvertUtil.addUrlEncodedStringIfArray(oldValue, value, encoding, cls,
                    paramConvert == null ? primitiveConvert : paramConvert);
            if (convertedValue != null) {
                BeanUtils.setProperty(pojo, name, convertedValue);
            }
        } else if (cls.equals(InputStream.class)) {
            Object convertedValue = item.getInputStream();
            if (convertedValue != null) {
                BeanUtils.setProperty(pojo, name, convertedValue);
            }
        } else if (cls.equals(FileItem.class)) {
            BeanUtils.setProperty(pojo, name, item);
        } else {
            logger.warn("Not support field[{}] type:{}.", name, cls);
        }
    } catch (IllegalAccessException e) {
        logger.error("can't invoke none-args constructor of a pojo of {}, please check the Pojo",
                pojo.getClass());
        throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
        logger.error("set pojo property error!", e);
        throw new RuntimeException(e);
    } catch (UnsupportedEncodingException e) {
        logger.error("can't convert stream to " + encoding, e);
        throw new RuntimeException(e);
    } catch (IOException e) {
        logger.error("getInputStream from item error!", e);
        throw new RuntimeException(e);
    }
}

From source file:gr.open.loglevelsmanager.loglevel.LogLevelUpload.java

public LogLevel uploadFiles(ActionRequest request, LogLevel logLevel)
        throws PortalException, SystemException, IOException, SecurityException, IllegalArgumentException,
        NoSuchMethodException, IllegalAccessException, InvocationTargetException {

    ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
    long userId = themeDisplay.getUserId();
    long groupId = UserLocalServiceUtil.getUser(userId).getGroupId();

    for (FileItem item : files) {
        String formField = item.getFieldName();
        String strType = formField.substring(formField.lastIndexOf(SEPARATOR) + 1);
        if (strType.equalsIgnoreCase(DOCUMENTFILE)) {
            String portletName = "_" + request.getAttribute(WebKeys.PORTLET_ID) + "_";
            formField = extractPrefixAndSufix(portletName, SEPARATOR + DOCUMENTFILE, formField);
            if (deleteds.get(formField) != null) {
                Long prevDocument = (Long) hiddens.get(HIDDEN + SEPARATOR + formField);
                if ((prevDocument != null) && (prevDocument != 0L)) {
                    PortletFileRepositoryUtil.deletePortletFileEntry(prevDocument);
                }//  w w  w.  j a va  2 s.  c  om
            } else if (!item.getName().equals("")) {

                long folderId = createFolders(request, userId, groupId, portletName);

                String sourceFileName = item.getName();
                InputStream inputStream = item.getInputStream();

                FileEntry fileEntry = PortletFileRepositoryUtil.addPortletFileEntry(groupId, userId,
                        LogLevel.class.getName(), logLevel.getPrimaryKey(), portletName, folderId, inputStream,
                        sourceFileName, StringPool.BLANK, true);

                callSetMethod(formField, logLevel, fileEntry.getFileEntryId());

                // Check possible previous values
                if (hiddens != null) {
                    Long prevDocument = (Long) hiddens.get(HIDDEN + SEPARATOR + formField);
                    if ((prevDocument != null) && (prevDocument != 0L)) {
                        // Delete previous document
                        PortletFileRepositoryUtil.deletePortletFileEntry(prevDocument);
                    }
                }
            } else {
                // See hidden value, possible edit
                if (hiddens != null) {
                    Long prevDocument = (Long) hiddens.get(HIDDEN + SEPARATOR + formField);
                    if ((prevDocument != null) && (prevDocument != 0L)) {
                        callSetMethod(formField, logLevel, (Long) hiddens.get(HIDDEN + SEPARATOR + formField));
                    }
                }
            }
        }
    }
    return logLevel;
}

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

/**
 * Overridden doPost method.//ww w  . java2s .  co 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.edgenius.wiki.ext.textnut.NutServlet.java

private String saveOrUpdatePage(HttpServletRequest request, HttpServletResponse response) {
    if (!doBasicAuthentication(request))
        return NutCode.AUTHENTICATION_ERROR + "";

    String spaceUname = null, title = null, pageUuid = null;
    InputStream content = null;/*from w  ww  .j  a va2  s.c  o m*/
    int version = 0;

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {
        @SuppressWarnings("unchecked")
        List<FileItem> items = upload.parseRequest(request);
        for (FileItem item : items) {
            String name = item.getFieldName();
            if (StringUtils.equals(name, "space")) {
                spaceUname = item.getString(Constants.UTF8);
            } else if (StringUtils.equals(name, "title")) {
                title = item.getString(Constants.UTF8);
            } else if (StringUtils.equals(name, "puuid")) {
                pageUuid = item.getString(Constants.UTF8);
            } else if (StringUtils.equals(name, "version")) {
                version = NumberUtils.toInt(item.getString(Constants.UTF8));
            } else if (StringUtils.equals(name, "content")) {
                content = item.getInputStream();
            }
        }

        log.warn("Nut service for page {} (UUID:{}) on space {}.",
                new String[] { title, pageUuid, spaceUname });
        if (content != null && spaceUname != null && title != null) {
            //parse BPlist
            Map<String, File> files = nutParser.parseBPlist(content);
            Space space = getSpaceService().getSpaceByUname(spaceUname);
            if (files != null && space != null) {
                File htmlFile = files.remove(NutParser.MAIN_RESOURCE_URL);
                if (htmlFile != null) {
                    String htmlText = nutParser.convertNutHTMLToPageHTML(FileUtils.readFileToString(htmlFile));

                    //save Page
                    Page page = new Page();
                    PageContent pageContent = new PageContent();
                    page.setContent(pageContent);
                    pageContent.setContent(getRenderService().renderHTMLtoMarkup(spaceUname, htmlText));
                    page.setPageUuid(pageUuid);
                    page.setTitle(title);
                    page.setSpace(space);
                    page.setVersion(version);

                    //upload attachments
                    if (files.size() > 0) {
                        if (pageUuid == null) {
                            //must get pageUUID first for upload attachment, so save page to draft first
                            Draft draft = getPageService().saveDraft(WikiUtil.getUser(), page.cloneToDraft(),
                                    PageType.AUTO_DRAFT);

                            pageUuid = draft.getPageUuid();
                            page.setPageUuid(pageUuid);

                            log.info("Nut save draft with new page uuid {}", pageUuid);
                        }
                        List<FileNode> attachments = new ArrayList<FileNode>();
                        for (File attach : files.values()) {
                            FileNode node = new FileNode();
                            node.setFilename(attach.getName());
                            node.setFile(new FileInputStream(attach));
                            node.setBulkZip(false);
                            node.setShared(false);
                            node.setIdentifier(pageUuid);
                            node.setCreateor(WikiUtil.getUserName());
                            node.setType(RepositoryService.TYPE_ATTACHMENT);
                            node.setStatus(PageType.NONE_DRAFT.value());
                            node.setComment("TextNut uploaded attached file");
                            //???node.setContentType(contentType);

                            attachments.add(node);

                            log.info("Uploading attachment {}", node.getFilename());
                        }
                        attachments = getPageService().uploadAttachments(spaceUname, pageUuid, attachments,
                                true);
                        page.setAttachments(attachments);

                        log.info("Nut uploaded attachments successfully.");
                    }

                    getPageService().savePage(page, WikiConstants.NOTIFY_ALL, true);

                    log.info("Nut save page {} by version {} successfully.", title, version);

                    getActivityLog().logPageSaved(page);
                    //return version:pageUUID combination. Version number must greater than 0
                    return page.getVersion() + ":" + page.getPageUuid();
                }
            }
        }

        log.warn("Nut save or update page {} (UUID:{}) failed on space {}.",
                new String[] { title, pageUuid, spaceUname });
        if (pageUuid == null) {
            return String.valueOf(NutCode.PAGE_CREATED_FAILED);
        } else {
            return String.valueOf(NutCode.PAGE_UPDATE_FAILED);
        }
    } catch (FileUploadException e) {
        log.error("Upload Nut file failed", e);
    } catch (UnsupportedEncodingException e) {
        log.error("Upload Nut file failed", e);
    } catch (IOException e) {
        log.error("Upload Nut file failed", e);
    } catch (PageException e) {
        log.error("Upload Nut file failed", e);
    } catch (VersionConflictException e) {
        log.error("Upload Nut file failed", e);
    } catch (PageSaveTiemoutExcetpion e) {
        log.error("Upload Nut file failed", e);
    } catch (DuplicatedPageException e) {
        log.error("Duplicate name for nut file.", e);
        return String.valueOf(NutCode.PAGE_DUPLICATED_TITLE);
    } catch (RepositoryException e) {
        log.error("Upload Nut file failed", e);
    } catch (RepositoryTiemoutExcetpion e) {
        log.error("Upload Nut file failed", e);
    } catch (RepositoryQuotaException e) {
        log.error("Upload Nut file failed", e);
    }

    return String.valueOf(NutCode.PAGE_UPDATED);
}

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

@Override
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doPost({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    String action = "";
    String userId = request.getRemoteUser();
    updateSessionManager(request);//from   w ww. ja va  2s.  co  m

    try {
        if (ServletFileUpload.isMultipartContent(request)) {
            InputStream is = null;
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            CronTab ct = new CronTab();

            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("ct_id")) {
                        ct.setId(Integer.parseInt(item.getString("UTF-8")));
                    } else if (item.getFieldName().equals("ct_name")) {
                        ct.setName(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("ct_mail")) {
                        ct.setMail(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("ct_expression")) {
                        ct.setExpression(item.getString("UTF-8"));
                    } else if (item.getFieldName().equals("ct_active")) {
                        ct.setActive(true);
                    }
                } else {
                    is = item.getInputStream();
                    ct.setFileName(FilenameUtils.getName(item.getName()));
                    ct.setFileContent(SecureStore.b64Encode(IOUtils.toByteArray(is)));
                    ct.setFileMime(MimeTypeConfig.mimeTypes.getContentType(item.getName()));
                    is.close();
                }
            }

            if (action.equals("create")) {
                CronTabDAO.create(ct);

                // Activity log
                UserActivity.log(userId, "ADMIN_CRONTAB_CREATE", null, null, ct.toString());
                list(request, response);
            } else if (action.equals("edit")) {
                CronTabDAO.update(ct);

                // Activity log
                UserActivity.log(userId, "ADMIN_CRONTAB_EDIT", Long.toString(ct.getId()), null, ct.toString());
                list(request, response);
            } else if (action.equals("delete")) {
                CronTabDAO.delete(ct.getId());

                // Activity log
                UserActivity.log(userId, "ADMIN_CRONTAB_DELETE", Long.toString(ct.getId()), null, null);
                list(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);
    }
}

From source file:edu.harvard.hul.ois.drs.pdfaconvert.service.servlets.PdfaConverterServlet.java

/**
 * Handles the file upload for PdfaConverter processing via streaming of the file
 * using the <code>POST</code> method. Example: curl -X POST -F datafile=@
 * <path/to/file> <host>:[<port>]/pdfa-converter/examine Note: "pdfa-converter" in the above URL
 * needs to be adjusted to the final name of the WAR file.
 *
 * @param request//  w ww .  j  a va  2s.c o  m
 *            servlet request
 * @param response
 *            servlet response
 * @throws ServletException
 *             if a servlet-specific error occurs
 * @throws IOException
 *             if an I/O error occurs
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    logger.info("Entering doPost()");
    if (!ServletFileUpload.isMultipartContent(request)) {
        ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_BAD_REQUEST,
                " Missing Multipart Form Data. ", request.getRequestURL().toString());
        sendErrorMessageResponse(errorMessage, response);
        return;
    }

    try {
        List<FileItem> formItems = upload.parseRequest(request);
        Iterator<FileItem> iter = formItems.iterator();

        // iterates over form's fields
        while (iter.hasNext()) {
            FileItem item = iter.next();

            // processes only fields that are not form fields
            // if (!item.isFormField()) {
            if (!item.isFormField() && item.getFieldName().equals(FORM_FIELD_DATAFILE)) {

                long fileSize = item.getSize();
                if (fileSize < 1) {
                    ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_BAD_REQUEST,
                            " Missing File Data. ", request.getRequestURL().toString());
                    sendErrorMessageResponse(errorMessage, response);
                    return;
                }
                // save original uploaded file name
                InputStream inputStream = item.getInputStream();
                String origFileName = item.getName();

                DiskFileItemExt itemExt = new DiskFileItemExt(item.getFieldName(), item.getContentType(),
                        item.isFormField(), item.getName(), (maxInMemoryFileSizeMb * (int) MB_MULTIPLIER),
                        factory.getRepository());
                // Create a temporary unique filename for a file containing the original temp filename plus the real filename containing its file type suffix.
                String tempFilename = itemExt.getTempFile().getName();
                StringBuilder realFileTypeFilename = new StringBuilder(tempFilename);
                realFileTypeFilename.append('-');
                realFileTypeFilename.append(origFileName);
                // create the file in the same temporary directory
                File realInputFile = new File(factory.getRepository(), realFileTypeFilename.toString());

                // strip out suffix before saving to ServletRequestListener
                request.setAttribute(TEMP_FILE_NAME_KEY, tempFilename.substring(0, tempFilename.indexOf('.')));

                // turn InputStream into a File in temp directory
                OutputStream outputStream = new FileOutputStream(realInputFile);
                IOUtils.copy(inputStream, outputStream);
                outputStream.close();

                try {
                    // Send it to the PdfaConverter processor...
                    sendPdfaConverterExamineResponse(realInputFile, origFileName, request, response);
                } finally {
                    // delete both original temporary file -- if large enough will have been persisted to disk -- and our created file
                    if (!item.isInMemory()) { // 
                        item.delete();
                    }
                    if (realInputFile.exists()) {
                        realInputFile.delete();
                    }
                }

            } else {
                ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_BAD_REQUEST,
                        " The request did not have the correct name attribute of \"datafile\" in the form processing. ",
                        request.getRequestURL().toString(), " Processing halted.");
                sendErrorMessageResponse(errorMessage, response);
                return;
            }

        }

    } catch (FileUploadException ex) {
        logger.error(ex);
        ErrorMessage errorMessage = new ErrorMessage(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                " There was an unexpected server error: " + ex.getMessage(), request.getRequestURL().toString(),
                " Processing halted.");
        sendErrorMessageResponse(errorMessage, response);
        return;
    }
}

From source file:com.meetme.plugins.jira.gerrit.adminui.AdminServlet.java

private File doUploadPrivateKey(final List<FileItem> items, final String sshHostname) throws IOException {
    File privateKeyPath = null;//from  ww  w .  j  a v  a 2s . co  m

    for (FileItem item : items) {
        if (item.getFieldName().equals(GerritConfiguration.FIELD_SSH_PRIVATE_KEY) && item.getSize() > 0) {
            File dataDir = new File(jiraHome.getDataDirectory(),
                    StringUtils.join(PACKAGE_PARTS, File.separatorChar));

            if (!dataDir.exists()) {
                dataDir.mkdirs();
            }

            String tempFilePrefix = configurationManager.getSshHostname();
            String tempFileSuffix = ".key";

            try {
                privateKeyPath = File.createTempFile(tempFilePrefix, tempFileSuffix, dataDir);
            } catch (IOException e) {
                log.info("---- Cannot create temporary file: " + e.getMessage() + ": " + dataDir.toString()
                        + tempFilePrefix + tempFileSuffix + " ----");
                break;
            }

            privateKeyPath.setReadable(false, false);
            privateKeyPath.setReadable(true, true);

            InputStream is = item.getInputStream();
            FileOutputStream fos = new FileOutputStream(privateKeyPath);
            IOUtils.copy(is, fos);
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(fos);

            item.delete();
            break;
        }
    }

    return privateKeyPath;
}